Using SaveFileDialog in c# Winforms - c#

I'm basically just trying to get a file path to save a file to but my SaveFileObject won't let me access the SelectedPath. I've checked the other forums and can't figure out why it won' tlet me, here's my code;
SaveFileDialog filePath = new SaveFileDialog();
DialogResult result = filePath.ShowDialog();
if (result == DialogResult.OK)
{
string folderPath = filePath.;
}
It'll let me select filePath.ShowDialog again and filePath.ToString etc... Where am I going wrong?

You actually want the file name from the FileName property from your SaveFileDialog. That will give you the full path and file name for the file your user wants to save.
SaveFileDialog saveDialog = new SaveFileDialog();
DialogResult result = saveDialog.ShowDialog();
if (result == DialogResult.OK)
{
String fileName = saveDialog.FileName;
//your code to save the file;
}
Although, since .ShowDialog() returns a DialogResult, you can use it directly in the if to spare one line of code (yup! I'm greedy)

Related

SaveFileDialog cannot find desktop folder path

I'm using SavefileDialog in C#. However, my SavefileDialog can't find the desktop folder path.
This is my code:
SaveFileDialog sfd = new SaveFileDialog();
DialogResult result = sfd.ShowDialog(this);
if( result == DialogResult.OK) {
// do something
}
Once SaveFileDialog is started, this error pops up:
Error: 'C:\Windows\system32\config\systemprofile\Desktop' refers to a location that is unavailable.
Why does the error pop up and how can I solve it?
To make SaveFileDialog open on particular directory, use InitialDirectory:
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DialogResult result = sfd.ShowDialog(this);
if (result == DialogResult.OK)
{
// do something
}
As for your error, please provide more details or at least the whole code of the method.

How to use openfiledialog to open any file as text in C#?

I am writing a winforms program in C# that uses the openfiledialog. I would like it to be able to take the file that the user selected and open it as text, regardless of the file type.
I tried it like this:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = Process.Start("notepad.exe", openFileDialog1.ToString()).ToString();
}
However, that didn't work and I'm not sure if I"m even on the right track.
You should use this code:
First add this namespace :
using System.IO;
Then add this codes to your function:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFileDialog.ShowDialog()== DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog.FileName);
}
To open the file using notepad, you need to pass the file name as second parameter of Start method. For example:
using (var ofd = new OpenFileDialog())
{
if(ofd.ShowDialog()== DialogResult.OK)
{
System.Diagnostics.Process.Start("notepad.exe", ofd.FileName);
}
}
Also if for any reason while knowing that not all file contents are text, you are going to read the file content yourself:
using (var ofd = new OpenFileDialog())
{
if(ofd.ShowDialog()== DialogResult.OK)
{
var txt = System.IO.File.ReadAllText(ofd.FileName);
}
}
What you are doing at the moment is starting a Process with the argument openFileDialog1.ToString(), calling ToString() on the process and setting this as text in the TextBox. If the path was valid, the result would probably be something like "System.Diagnostics.Process". But since you use openFileDialog1.ToString() as a path, your application probably crashes with a file not found error.
To get the selected file of an OpenFileDialog, use openFileDialog1.FileName. (See the docs here)
What I think you actually want to do, is read from the file and write its contents as text to the TextBox. To do this, you need a StreamReader, like so:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
using(var reader = new StreamReader(openFileDialog1.FileName))
{
textBox1.Text = reader.ReadToEnd();
}
}
This way, you open the file with the StreamReader, read its contents and then assign them to the text box.
The using statement is there because a StreamReader needs to be disposed of after you're done with it so that the file is no longer in use and all resources are released. The using statement does this for you automatically.

Make user browse and select a txt file for processing in c#

I want the user to locate a txt file on his computer which will later be used by my code for analysis. Is there a way to do that? One possible way is to make user enter the path of txt file. But that's not how I would prefer it
Thanks
string filename;
var loadDialog = new OpenFileDialog { Filter = "Text File|*.txt", InitialDirectory = #"C:\Your\Start\Directory\" };
if (loadDialog.ShowDialog() == DialogResult.OK)
filename = loadDialog.FileName;

Save File Dialog , restrict name

my program has a save file option which is shown below :
//Browse for file
SaveFileDialog ofd = new SaveFileDialog();
ofd.Filter = "CSV|*.csv";
ofd.DefaultExt = ".csv";
DialogResult result = ofd.ShowDialog();
string converted = result.ToString();
if (converted == "OK")
{
Master_Inventory_Export_savePath.Text = ofd.FileName;
}
if I write the file name as "example" it saves correctly as a .csv however if I set the name as "example.txt" it saves as a text file , I've looked on msdn etc but even setting the default extension doesn't prevent this , any ideas on how to only allow files of .csv to be saved ?
You could use the FileOk event to check what your user types and refuse the input if it types something that you don't like.
For example:
SaveFileDialog sdlg = new SaveFileDialog();
sdlg.FileOk += CheckIfFileHasCorrectExtension;
sdlg.Filter = "CSV Files (*.csv)|*.csv";
if(sdlg.ShowDialog() == DialogResult.OK)
Console.WriteLine("Save file:" + sdlg.FileName);
void CheckIfFileHasCorrectExtension(object sender, CancelEventArgs e)
{
SaveFileDialog sv = (sender as SaveFileDialog);
if(Path.GetExtension(sv.FileName).ToLower() != ".csv")
{
e.Cancel = true;
MessageBox.Show("Please omit the extension or use 'CSV'");
return;
}
}
The main advantage of this approach is that your SaveFileDialog is not dismissed and you could check the input without reloading the SaveFileDialog if something is wrong.
BEWARE that the SaveFileDialog appends automatically your extension if it doesn't recognize the extension typed by your user. This means that if your user types somefile.doc then the SaveFileDialog doesn't append the .CSV extension because the .DOC extension is probably well known in the OS. But if your user types somefile.zxc then you receive as output (and also in the FileOk event) a FileName called somefile.zxc.csv
can you not just force the .csv filetype by going like so in the last block of code?
if (converted == "OK")
{
if (ofd.FileName.toString.EndsWith(".csv")<1)
{
Master_Inventory_Export_savePath.Text = ofd.FileName + ".csv";
}
else
{
Master_Inventory_Export_savePath.Text = ofd.FileName;
}
}
Note - untested, but should give you a starting point....
Set the property AddExtension to true.
ofd.AddExtension = true;

Win Form: SaveFileDialog

I added the following piece of code to a save button:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
StreamWriter writer = new StreamWriter(fs);
writer.Write(twexit.Text); // twexit is previously created
writer.Close();
fs.Close();
}
When I type the name of the file and click save, it says that file does not exist. I know it does not exist but I set FileMode.Create. So, shouldnt it create file if it does not exist?
There is an option CheckFileExists in SaveFileDialog which will cause the dialog to show that message if the selected file doesn't exist. You should leave this set to false (this is the default value).
You can simply use this:
File.WriteAllText(saveFileDialog1.FileName, twexit.Text);
instead of lot of code with stream. It create new file or overwrite it.
File is class of System.Io . If you want to say if file exist, use
File.Exist(filePath)
Bye
Use like this:
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "csv files (*.csv)|*.csv";
dlg.Title = "Export in CSV format";
//decide whether we need to check file exists
//dlg.CheckFileExists = true;
//this is the default behaviour
dlg.CheckPathExists = true;
//If InitialDirectory is not specified, the default path is My Documents
//dlg.InitialDirectory = Application.StartupPath;
dlg.ShowDialog();
// If the file name is not an empty string open it for saving.
if (dlg.FileName != "")
//alternative if you prefer this
//if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK
//&& dlg.FileName.Length > 0)
{
StreamWriter streamWriter = new StreamWriter(dlg.FileName);
streamWriter.Write("My CSV file\r\n");
streamWriter.Write(DateTime.Now.ToString());
//Note streamWriter.NewLine is same as "\r\n"
streamWriter.Write(streamWriter.NewLine);
streamWriter.Write("\r\n");
streamWriter.Write("Column1, Column2\r\n");
//…
streamWriter.Close();
}
//if no longer needed
//dlg.Dispose();

Categories