OpenFileDialog only select file path - c#

I am trying to use a OpenFileDialog to let the user select a local file that can interact with my app. The file can be in use when the user selects it as I really only want to get the file's path. My issue is that if I try doing this with a OpenFileDialog, when the user presses "open", it actually tries to open the file even though I don't call for opening anywhere. Since the file is in use, it throws an error.
Is there any way for me to present a dialog for a user to just select a file an do nothing else?
Heres my current code:
DialogResult result = this.qbFilePicker.ShowDialog();
if (result == DialogResult.OK)
{
string fileName = this.qbFilePicker.FileName;
Console.WriteLine(fileName);
}

Make sure you are using
using System.Windows.Forms;
Then the following code from MSDN will not open your file unless you explicitly uncomment the bit that opens the file :)
(Take out the bits that don't pertain to you such as the .txt filter etc)
private void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileName = openFileDialog1.FileName;
Console.WriteLine(fileName);
//to open the file
/*
try
{
Stream myStream = null;
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
* */
}
}

Related

Using open file dialog to choose the file location of a text file and use it in stream reader

I am trying to make a try catch that will check if the file in filelocation exists or not.
If it doesnt i want the open file dialog to open and allow user to be able choose the text file (and only a text file) and read the file location of the selected file and use that as the file location sting for the sream reader
any time i use this the file location will be right until the end. instead of the file name it will have bin/debug/ok
try
{
if (!File.Exists(filelocation))
{
throw new FileNotFoundException();
}
else
{
StreamReader question = new StreamReader(filelocation);
}
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File containing the questions not found");
OpenFileDialog OFD = new OpenFileDialog();
DialogResult result = OFD.ShowDialog();
string filelocation = result.ToString();
StreamReader question = new StreamReader(filelocation);
}
add this
OFD .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
the result will be:
try
{
if (!File.Exists(filelocation))
{
throw new FileNotFoundException();
}
else
{
StreamReader question = new StreamReader(filelocation);
}
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File containing the questions not found");
OpenFileDialog OFD = new OpenFileDialog();
OFD .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
DialogResult result = OFD.ShowDialog();
string filelocation = result.ToString();
StreamReader question = new StreamReader(filelocation);
}
This takes into account whether User did not select a File from the File Dialog or whether invalid file is selected...
StreamReader ReadME;
if (!File.Exists(termfilelocation))
{
MessageBox.Show("File containing the questions not found");
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
// this will filter out any file that isnt a text file
ofd.CheckFileExists = true;//this will not allow invalid files.
DialogResult dr = OFD.ShowDialog();
if (dr == DialogResult.Cancel)
{
//User did not select a file.
return;
}
String result = OFD.FileName;
ReadME = new StreamReader(result);
termfilelocation = result;
}
else
{
ReadME = new StreamReader(termfilelocation);
}
I fixed it myslef so anybody having similar problems heres how to fix it
try
{
if (!File.Exists(termfilelocation))
{
throw new FileNotFoundException();
}
else
{
StreamReader reader = new StreamReader(termfilelocation);
}
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("File containing the questions not found");
// this will display a message box sying whats in ("")
OpenFileDialog OFD = new OpenFileDialog();
// this will create a new open file dialog box
OFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
// this will filter out any file that isnt a text file
DialogResult = OFD.ShowDialog();
String result = OFD.FileName;
// this will give the result to be the file name
// that was choosen in the open file dialog box
StreamReader reader = new StreamReader(result);
termfilelocation = result;
}

how to retrieve file data(.txt) to respective text box?

in my code i am writing text boxes data to a text file using save file dialog, which will save my text box data to a specified text file.and my problem is i need to retrieve back file data to respective text boxes when ever user required ...how can i do it?
private void SaveData_Click(object sender, EventArgs e)
{
// Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = "c:\\";
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
using (StreamWriter objWriter = new StreamWriter(myStream))
{
objWriter.Write(textBox1.Text);
objWriter.Write(",");
objWriter.Write(textBox2.Text);
objWriter.Write(",");
objWriter.Write(textBox3.Text);
objWriter.Write(",");
objWriter.Write(textBox4.Text);
MessageBox.Show("Details have been saved");
}
myStream.Close();
}
}
}
private void Retrieve_Click(object sender, EventArgs e)
{
//Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
textBox1.Text = (myStream).ToString();
textBox2.Text = ().ToString();
textBox3.Text = ().Tostring();
textBox4.text = ().Tostring();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
You need to use an OpenFileDialog Control and pass it to the ReadAllText Method ..
Here is an Example :
myAmazingTextBox.Text = File.ReadAllText(openFileDialog1.FileName);
Save the location where user saves data.\
Next time you should read the path first.
You can save the saveFileDialog1.FileName.
Use the code below to retrieve the text saved in the file (code changed within try block)
private void Retrieve_Click(object sender, EventArgs e)
{
//Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
// Read all text stored in the file
string fileData = File.ReadAllText(openFileDialog1.FileName);
// As you are appending textbox data using comma as separator,
// so split the text read from file on comma separator
string[] parts = fileData.Split(',');
// as there were 4 textboxes, so after split, the 'parts' array should contain 4 elements, otherwise, the file/data is invalid
if(parts.Length != 4)
{
MessageBox.Show("Invalid source file.");
return;
}
// set the respective values into the textboxes
textBox1.Text = parts[0];
textBox2.Text = parts[1];
textBox3.Text = parts[2];
textBox4.text = parts[3];
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
I would like to suggest that you don't use comma as a separator as the user may enter text which contains comma in the content. I would suggest that you encode the text into Base64 string (which contains only A-Za-z0-9 with additional two characters which does not contain comma. So, you can separate the base64 encoded string with comma separator as then you will be 100% sure that comma is only the separator and not the part of content.
While reading, decode the base64 string and show into textboxes.

Save filedialog not working

Bit of an odd one here , I'm writing an app which gives a save file option , the save file dialog is coded up as normal
SaveFileDialog ofd = new SaveFileDialog();
the dialog box comes up no problem and clicking save doesn't throw up any errors however no file is saved and I'm not sure why , any ideas ? I've googled it and can't find a similar problem
The SaveFileDialog class doesn't save anything, it prompts the user to choose a location and a file name to save the file. It is your job to save the file
This example extracted from the MSDN link above explains the concept
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
Stream stream;
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
ofd.FilterIndex = 2 ;
ofd.RestoreDirectory = true ;
if(ofd.ShowDialog() == DialogResult.OK)
{
if((stream = ofd.OpenFile()) != null)
{
//FileStream might be better for you but since i don't know what you write, this will serve as an example
stream.Write(bytes,offset,count);
stream.Close();
}

C# - Read .txt file into TextBox

I am trying to read a .txt file into a multi-line text box with the following code. I have gotten the file dialog button to work perfectly, but I am not sure how to get the actual text from the fiile into the textbox. Here is my code. Can you help?
private void button_LoadSource_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
if you just need the complete text, you should use the function File.ReadAllText - pass it the FileName/Path selected in the dialoge (openFileDialog1.FileName).
to load for example the content into a textbox, you can write:
textbox1.Text = File.ReadAllText(openFileDialog1.FileName);
opening and using streams is a little bit more complicated, for that you should look up the using - statement

Obtain file path of C# save dialog box

I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later.
Can anybody tell me how to obtain the file path from the save dialog box to use it later?
Here is a sample code I just wrote very fast... instead of Console.Write you can simply store the path in a variable and use it later.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 1;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Console.WriteLine(saveFileDialog1.FileName);//Do what you want here
}
Addressing the textbox...
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = saveFileDialog.FileName;
}
private void mnuFileSave_Click(object sender, EventArgs e)
{
dlgFileSave.Filter = "RTF Files|*.rtf|"+"Text files (*.txt)|*.txt|All files (*.*)|*.*";
dlgFileSave.FilterIndex = 1;
if (dlgFileSave.ShowDialog() == System.Windows.Forms.DialogResult.OK && dlgFileSave.FileName.Length > 0)
{
foreach (string strFile in dlgFileSave.FileNames)
{
SingleDocument document = new SingleDocument();
document.rtbNotice.SaveFile(strFile, RichTextBoxStreamType.RichText);
document.MdiParent = this;
document.Show();
}
}
}
Try below code.
saveFileDialog1.ShowDialog();
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);

Categories