Win Form: SaveFileDialog - c#

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();

Related

Using SaveFileDialog in c# Winforms

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)

Save DIalogue that copies/loads another file

I am trying to save a file, but the actual file is already built and saved in a temp location, and I just want to move/copy that pre-built file to wherever the user chooses with the save dialogue.
What I have right now is this
fileName = the pathway of the file that is already built.
private void SaveFile()
{
SaveFileDialog savefile = new SaveFileDialog();
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(savefile.FileName))
sw.WriteLine(fileName);
}
}
Obviously right now this just writes the pathway to a text file, but I am trying to find a way to basically copy that file to wherever this user specifies.
you can do like
if (savefile.ShowDialog() == DialogResult.OK)
{
// you can use File.Copy
System.IO.File.Copy(fileName, saveFile.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;

Saving Stream.Write to existing .CSV file doesn't replace data, only adds to existing data. How do I only replace the data?

The following code is used to save a CSV string, however, if I save to an existing .CSV, instead of replacing the data, it only adds the new string to the data already there.
How do I remedy this? Is it something inherent to how the Stream.Write function works, or is this an idiosyncrasy of Excel and .CSV?
SaveFileDialog dialog = new SaveFileDialog();
dialog.AddExtension = true;
dialog.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
dialog.FilterIndex = 1;
dialog.Title = "Save As";
dialog.InitialDirectory = "C:\\";
dialog.CheckPathExists = true;
dialog.DefaultExt = ".csv";
dialog.ValidateNames = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
StreamWriter myStream = new StreamWriter(dialog.FileName, true);
myStream.Write(//Function which returns a CSV-formmatted string//);
myStream.Close();
OpenFile(dialog.FileName);
}
StreamWriter myStream = new StreamWriter(dialog.FileName, false);
http://msdn.microsoft.com/library/36b035cb%28v=vs.100%29
the second parameter (bool append), is well described :
append
Type: System.Boolean
Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file
exists and append is true, the data is appended to the file.
Otherwise, a new file is created.
Set append to false, that way, StreamWriter will overwrite the file, rather than appending the data to it.
StreamWriter myStream = new StreamWriter(dialog.FileName, false);
In new StreamWriter(dialog.FileName, true) change true to false
Intellisence will tell you what your parameters are named as you type the function call, and it might give you a tooltip about what they mean. You should pay attention to that
I believe that simply typing new StreaWriter(dialog.FileName) will set append to false by default.
Pass the proper parameter to the constructor:
new StreamWriter(
path: path
append: false);

File Open/Save Dialog

I am using my own Custom View to show the files and folders and also using a search box to jump to a specific folder. In that case How to send a message to File Open/Save dialog to enforce it to change the current displayed folder.
e.g. If the dialog shows files and folders of current displaying folder "C:\", I want an API (or any piece of code) to enforce to change the current folder to "D:\"
You can have the dialog open at a specific directory using InitialDirectory.
If you want to control what the dialog does at runtime, that's a bit more complex.
Set SaveFileDialog.InitialDirectory after you create it, but before you open it.
For example:
Stream myStream = null;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1 .InitialDirectory = "d:\\" ;
saveFileDialog1 .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1 .FilterIndex = 2 ;
saveFileDialog1 .RestoreDirectory = true ;
if(saveFileDialog1 .ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = saveFileDialog1 .OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not save file to disk. Original error: " + ex.Message);
}
}
set InitialDirectory property to any path

Categories