How can I check if the path entered by user is valid or not? [duplicate] - c#

This question already has answers here:
Check whether a path is valid
(12 answers)
Closed 8 years ago.
I have found this code while I was busy searching for an answer!
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse.Title = "Save an pcap File";
saveFileDialogBrowse.ShowDialog();
var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
if (pcapFile != "")
{
FileInfo fileInfo = new FileInfo(pcapFile);
txtFilePath.Text = fileInfo.FullName;
}
}

There is no easy way.
You can use File.Exists to check for file existence on the path, but a change can still happen before the execution of the next line. Your best option is to combine File.Exists with try-catch to catch any possible exceptions.
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
saveFileDialogBrowse.Title = "Save an pcap File";
saveFileDialogBrowse.ShowDialog();
var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
try
{
if (File.Exists(pcapFile))
{
FileInfo fileInfo = new FileInfo(pcapFile);
txtFilePath.Text = fileInfo.FullName;
}
}
catch (FileNotFoundException fileNotFoundException)
{
//Log and handle
}
catch (Exception ex)
{
//log and handle
}
}

You can use the File.Exists method:
string fullPath = #"c:\temp\test.txt";
bool fileExists = File.Exists(fullPath);

You can use the File.Exists method, which is documented here.

Related

openfiledialog results in file is being used by another process [duplicate]

This question already has an answer here:
System.IO.IOException: 'The process cannot access the file because it is being used by another process
(1 answer)
Closed 2 years ago.
I would like use C# to upload multiple files to google drive
this is my upload button function
private void bt_upload_Click(object sender, EventArgs e)
{
Filedialog_init();
DialogResult check_upload = MessageBox.Show("Want to upload these files ?", "Upload", MessageBoxButtons.OKCancel);
if (check_upload == DialogResult.OK)
{
for (int i = 0; i < result.Count; i++)
{
UploadFilesDrive(service, result[i], filePath[i], Datatype[i]);
tx_state.AppendText(result[i] + "Upload Done");
}
}
}
This is my Filedialog_init function
private static void Filedialog_init()
{
Stream myStream = null;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filename = null;
string _datatype = null;
try
{
if ((myStream = openFileDialog.OpenFile()) != null)
{
foreach (String file in openFileDialog.FileNames)
{
filename = Path.GetFileName(file);
result.Add(filename);
// only show the name of file
Datatype.Add(_datatype);
}
filePath = openFileDialog.FileNames;
Datatype.ForEach(Console.WriteLine);
}
openFileDialog.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
else
MessageBox.Show("Upload Cancel");
}
I can upload the file successfully by assigning the filename and its datatype and path directly
But when I used openfiledialog,it went wrong with "my file is being used by another process"
How can I solve this problem?
Issue lies in your code here,
(myStream = openFileDialog.OpenFile()) This line is keeping lock on the file because your myStream does not get disposed. you need to dispose the stream as soon as you are done with it.
So try with using as it will dispose the stream as soon as your end using line gets executed. More details on using.
you can try as below,
using(Stream myStream = openFileDialog.OpenFile())
{
//Your code here...
}

Savefiledialog locked file, change file name

How to keep the savefilediallog open when you write to a file which is in use by an other program so that you can change the file name and try to save again?
private void button1_Click_2(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
CsvExport = Class_ExportData.DataTableToCSV(datatabelControle, csvSCheidingteken);
Cursor.Current = Cursors.Default;
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.Filter = "Komma gescheiden waarden (*.csv)|*.csv|Tekst bestanden (*.txt)|*.txt|Alle formaten (*.*)|*.*";
saveFileDialog1.DefaultExt = "csv";
saveFileDialog1.AddExtension = true;
saveFileDialog1.ShowDialog();
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
try
{
string name = saveFileDialog1.FileName; // Get file name.
File.WriteAllText(name, CsvExport); // Write to the file name selected.
}
catch (Exception ex)
{
//file is locked, how to get back to the open save file dialog ???
}
}
Try this. Move the code associated with opening the saveFileDialog1 into its own function and invoke that function from button1_Click:
private void button1_Click_2(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
CsvExport = Class_ExportData.DataTableToCSV(datatabelControle, csvSCheidingteken);
Cursor.Current = Cursors.Default;
ShowSaveFileDialog();
}
private void ShowSaveFileDialog()
{
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.Filter = "Komma gescheiden waarden (*.csv)|*.csv|Tekst bestanden (*.txt)|*.txt|Alle formaten (*.*)|*.*";
saveFileDialog1.DefaultExt = "csv";
saveFileDialog1.AddExtension = true;
saveFileDialog1.ShowDialog();
}
EDIT: On further consideration, I don't think you want/need the loop here, so I've removed it. You still want to invoke the ShowSaveFileDialog method here in case of exceptions, though:
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
try
{
string name = saveFileDialog1.FileName; // Get file name.
File.WriteAllText(name, CsvExport); // Write to the file name selected.
return;
}
catch (Exception ex)
{
//file is locked, how to get back to the open save file dialog ???
// maybe display an error message here so that the user knows why they're about to see the dialog again.
}
ShowSaveFileDialog();
}
Technically, this can probably lead to a StackOverflowException if the user tries repeatedly (and I mean thousands of times) to retry the save after an exception, but that's pretty unlikely.

C# WPF FileSaving Exception encountered

My issue is that I keep seeing a recurring theme with trying to allow my Notepad clone to save a file. Whenever I try to save a file, regardless of the location on the hard disk, the UnauthorizedAccess Exception continues to be thrown. Below is my sample code for what I've done, and I have tried researching this since last night to no avail. Any help would be greatly appreciated.
//located at base class level
private const string fileFilter = "Text Files|*.txt|All Files|*.*";
private string currentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private void MenuFileSaveAs_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "*.txt";
sfd.Filter = fileFilter;
sfd.AddExtension = true;
sfd.InitialDirectory = currentPath;
sfd.RestoreDirectory = true;
sfd.OverwritePrompt = true;
sfd.ShowDialog();
try
{
System.IO.File.WriteAllText(currentPath,TxtBox.Text,Encoding.UTF8);
}
catch (ArgumentException)
{
// Do nothing
}
catch(UnauthorizedAccessException)
{
MessageBox.Show("Access Denied");
}
}
Change the following lines.
...
if (sfd.ShowDialog() != true)
return;
try
{
using (var stream = sfd.OpenFile())
using (var writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.Write(TxtBox.Text);
}
}
...
I hope it helps you.
You need to get the correct path context and file object from the dialog box once the user has hit 'ok'. Namely verify the user actually hit ok and then use the OpenFile property to see what their file selection is:
if (sfd.ShowDialog.HasValue && sfd.ShowDialog)
{
if (sfd.OpenFile() != null)
{
// convert your text to byte and .write()
sfd.OpenFile.Close();
}
}

display file instead of RSC version

Whenever I try to open a custom file to a textbox or something which will display code. it never works, I'm not sure what I am doing wrong.
I want my program to display what is inside the file when I open it, I have this below:
private void button1_Click(object sender, EventArgs e)
{
//Show Dialogue and get result
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "rbt files (*.rbt)|*.rbt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show("RBT7 file open");
}
}
}
It only displays the RBT7 in a messagebox which is not what I want, I want the file to open and display its information to some sort of textbox which displays code.
Please read the documentation for File.WriteAllText.
The first parameter:
path: The file to write to.
You're passing it "". That is not a path. Are you trying to write all the text from the file into CodeBox.Text or write all the text from CodeBox.Text into a file?
In your comment, you indicate the former. Try this:
string[] lines = System.IO.File.ReadAllLines(#"your file path");
foreach (string line in lines)
{
CodeBox.Text += line;
}
You haven't shown the code for CodeBox so I can't guarantee the results of this.
Try this:
Replace this code
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
with this
{
CodeBox.Text = File.ReadAllText(openFileDialog1.FileName);
}

how do I recall a string from a different function?

I am having trouble calling the string "rlist" from:
public void main()
{
string rlist;
if (radioButton1.Checked)
textBox1.Enabled = false;
textBox1.ReadOnly = true;
rlist = "text";
}
to
public void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "WTF Files (*.wtf)|*.wtf";
openFile.Title = "Please Pick your realmlist file:";
if (openFile.ShowDialog() == DialogResult.Cancel)
return;
try
{
textBox5.Text = openFile.FileName;
string file = openFile.FileName;
TextWriter rlist_writer = new StreamWriter (openFile.FileName);
rlist_writer.WriteLine(rlist);
rlist_writer.Close();
}
catch (Exception)
{
MessageBox.Show("Error opening file", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
I get the error on this line:
rlist_writer.WriteLine(rlist);
is it possible to call a string from one function and send it to the other with the same value it had in the function it was originally pulled from?
By the sounds of your question,
Your string is local to your main function.
So judging by your method names and knowledge of winforms(presumed again)
you need to make your string class level
string rlist;
public void main()
{
rlist = "yay"
public void button1_Click(object sender, EventArgs e)
{
someText = rlist;
As it currently stands you are not able to, as temporary (local) variables will be cleaned through garbage collection when you leave the method
Edit
You may wish to review this also
try
{
textBox5.Text = openFile.FileName;
using(TextWriter rlist_writer = new StreamWriter (openFile.FileName))
{
rlist_writer.WriteLine(rlist);
}
}
You can define that variable in your class scope, then if you call that variable in your button_click event, it will maintain the same value as in your main method.

Categories

Resources