Save Dialog Message and Empty path names - c#

I am currently working Open file and write file functions in C#. I am going through two problems: When the user is in the process of saving a file, if he/she exits the save dialog and nothing is saved I get an error(look at picture below for description). How can my program avoid this and not crash? and Is there away to display a message after the file has been saved?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog saveReport = new SaveFileDialog();
saveReport.Filter = "Text Files | *.txt";
saveReport.ShowDialog();
StreamWriter writeFile = new StreamWriter(saveReport.FileName);
writeFile.Write(textBox1.Text);
writeFile.Close();
}

If the user clicks Cancel, ShowDialog() will return DialogResult.Cancel.
You can check for this in an if statement.

You could do something like this:
var saveReport = new SaveFileDialog();
saveReport.Filter = "Text Files | *.txt";
var result = saveReport.ShowDialog();
if(result == DialogResult.Cancel || string.IsNullOrWhiteSpace(saveReport.FileName))
return;
using(var writer = new StreamWriter(saveReport.FileName))
{
writer.Write(textBox1.Text);
writer.Close();
}
MessageBox.ShowDialog("File Saved!");
In principle the FileName will never be null or whitespace -- the dialog prevents it unless you cancel, but I include it for clarity.

Use the return value of your ShowDialog call to determine what the user selected.
The code below saves only if the user selected OK in the dialog:
SaveFileDialog saveReport = new SaveFileDialog();
saveReport.Filter = "Text Files | *.txt";
if (saveReport.ShowDialog() == DialogResult.OK) {
StreamWriter writeFile = new StreamWriter(saveReport.FileName);
writeFile.Write(textBox1.Text);
writeFile.Close();
}
The problem with your original code was that you were attempting to save even if the user did not specify a file name through the dialog.

Related

Save under a filename once, and then save under same filename without dialog popping up asking for filename?

I wish to avoid popping up the dialog for each save attempt and choose a filename once, and save without asking for filename after?
Ideally the app should show the dialog once, save the filename. Then encapsulate code saving data into a method, make the filename visible to it, and call it when needed.
Not sure how to do this.
private void SaveData() //Figure out how to remeber previous save name
{
string taxpayerLine;
string taxpayerFile;
SaveFileDialog taxpayerFileChooser;
StreamWriter fileWriter;
taxpayerFileChooser = new SaveFileDialog();
taxpayerFileChooser.Filter = "All text files|*.txt";
if (taxpayerFileChooser.ShowDialog() == DialogResult.OK)
{
taxpayerFile = taxpayerFileChooser.FileName;
taxpayerFileChooser.Dispose();
fileWriter = new StreamWriter(taxpayerFile, true);
foreach (Taxpayer txp in taxpayerBindingSource)
{
taxpayerLine = txp.Display(",");
fileWriter.WriteLine(taxpayerLine);
}
fileWriter.Close();
fileWriter.Dispose(); //Destructor
MessageBox.Show("Data Saved to: "
+ System.IO.Path.GetFileNameWithoutExtension(taxpayerFile));

Bypassing save dialog box in WPF application

I am trying to bypass the save dialog box when using the SaveFileDialog class. I want to be able to write to a document without having to prompt a user to decide if they want to save or not, the file should automatically save when they click a button.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.RestoreDirectory = true ;
saveFileDialog1.InitialDirectory = #"C:\";
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// Code to write the stream goes here.
}
I have tried removing the if statement as well as using...
saveFileDialog1.CreatePRompt = false;
Nothing seems to work... Any ideas?
I think you want to bypass the overwrite prompt dialog.
In this case you can use
saveFileDialog1.OverwritePrompt = false;
Otherwise, you don't need a SaveFileDialog and you can save your stream without using it.
I found my answer. The question I asked was actually two it seems. The first was how to bypass SaveFileDialog, I wanted to use saveFileDialog because it can remember the last folder it accessed and opens to that folder when performing a read/save. That being said I implemented this...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
This will set Directory to the location of my executable.
Next I got rid of SaveFileDialog and just wrote to a file without ever prompting the user.
Thanks for all the pointers and ideas!
The end result ended up...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
using(System.IO.StreamWriter file = new System.IO.StreamWriter(Directory, false))
{
// File contents
}
Works perfectly for what I need it for.
If you want to save but you need the user to pick a filename, I would use this:
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//setup properties of Dialog
bool filenamepicked = false;
while (!filenamepicked)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//Save file
filenamepicked = true;
}
else
{
MessageBox.Show("You have to use a file name.");
}
}

Creating and saving files in C#

I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension.
In plain english I would like to know how to:
-Create a .dat file
-Write to it
-And save the file using SaveFileDialog
There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn.
The following code is what I have at the moment. Basically it opens a SaveFileDialog window with a blank File: section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
Pages that I've been looking at:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
Note that the SaveFileDialog only yields a filename but does not actually save anything.
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
Use the filename you are getting from the SaveFileDialog and do the following:
File.WriteAllText(filename, contents);
That's all if you intend to write text to the file.
You can also use:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}

allowing only pdf files to be uploaded

I have a browse button in my windows form application and i wanted to only filter down to the option of choosing pdf files. So in the browse file window only pdf files will be visible and not showing .doc or any kind of document format.
private void btnSelectFile_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
var res = dlg.ShowDialog();
if (res == DialogResult.OK)
{
DocumentUNCPath.Text = dlg.FileName;
}
}
Firstly you need to apply a filter first to the OpenFileDialog such as:
dlg.Filter = "PDF Files|*.pdf";
However, that doesn't stop them from forcing through a file (which they can do). You can again check the filename again after they click on OK but this is no guarantee that the file you get will be a PDF.
To be safe you could use a PDF library either locally or server side to try and open the PDF file and see if it really is such.
Add this:
dlg.Filter = "PDF files|*.pdf";
You'll want to set the filter property on your dlg object like this:
var dlg = new OpenFileDialog();
dlg.Filter = "*.pdf";
var res = dlg.ShowDialog();
if (res == DialogResult.OK)
{
DocumentUNCPath.Text = dlg.FileName;
}
You want to use the Filter property of the OpenFileDialog.
dlg.Filter = "PDF Files|*.pdf"
The portion to the left of the | can be anything, I just gave you an example, but it's what's shown to the user. The portion to the right of the | is the actual Windows filter.

How to show a message box on an invalid filename entered while saving a file using save file dialog

Hi all i have written a code to display a message box if invalid characters are entered while saving the file but my message box is not displaying. Actually i will have a save file dialog option to save a file if the filename starts or consists of the following
\\/:*?<>|"
I would like to display a message box as invalid or illegalcharacters in file
My code is as follows
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "(*.txt)|*.txt";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileName = saveFileDialog1.FileName;
if ((FilePathHasInvalidChars(FileName)))
{
MessageBox.Show("File name should not contain \\/:*?<>|" ,"", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
//FileName = saveFileDialog1.FileName;
if (!(FilePathHasInvalidChars(FileName)))
{
TreeNode newNode = new TreeNode(FileName);
newNode.SelectedImageIndex = 1;
tvwACH.SelectedNode.Nodes.Add(newNode);
TreeNode NodeFileHeader = newNode.Nodes.Add("FileHeader");
myStream.Close();
}
}
}
}
public static bool FilePathHasInvalidChars(string path)
{
return (!string.IsNullOrEmpty(path) && path.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0);
}
Can any one help me
The SaveFileDialog class has a property called ValidateNames. It the value of that property is true(which it is by default, no need to assign it), the dialog will automatically validate that the name the the user enters does not contain any illegal characters. If the user enters an illegal file name and clicks the "Save" button, the dialog will not close, but instead show an error message:
(yes, I am currently using Windows XP)
This is because the FileDialog does this check already on himself.
If you try to use a < or a > within a filename you get an error message. If you try to use a search pattern like ? or * the ListView will be filtered for the given pattern.
Set the property ValidateNames to true in the saveFileDialog1 instance as per this MSDN. And that is set to default to be true at run-time instantiation of the 'SaveFileDialog' class.
If you're talking about having a customized error message handler to display a custom message, you need to override the SaveFileDialog by sub-classing it and intercepting the windows procedure messages for this class. Have a look at this article on CodeProject which shows how to do it.

Categories

Resources