Avoid exception when writing to null file - c#

I'm doing some WPF exercises and I could succesfully write a file with content on it.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text file (*.txt)|*.txt";
sfd.ShowDialog();
using (StreamWriter sw = File.CreateText(sfd.FileName))
{
sw.Write(container.Text);
sw.Close();
}
MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString());
container.ResetText();
That using (StreamWriter) is rising the exception.
If I try to save a file, but, close the window before informing a file name , things go bad.
How can I avoid that ? I tried checking if the file is null ( both above and inside the using statement but it still goes off.

You need to check the result of ShowDialog:
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text file (*.txt)|*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(sfd.FileName, container.Text);
MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString());
container.ResetText();
}

Related

How to delete file after success copy

I am trying to to delete file after successful copy.
I want the original file to be deleted after I copied it.
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "All Files(*.*)|*.*";
if (open.ShowDialog() == DialogResult.OK)
{
string filename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + id.ToString()+Path.GetExtension(open.FileName);
if (!Directory.Exists(Application.StartupPath + "\\AttachedFiles"))
{
Directory.CreateDirectory(Application.StartupPath + "\\AttachedFiles");
}
File.Copy(open.FileName, Path.Combine(Application.StartupPath + "\\AttachedFiles", filename));
cnx.ExecuteCmd("insert into Attachement values('" + id + "','" + filename + "','" + Path.GetFileName(open.FileName) + "')");
MessageBox.Show("attached success");
listBox1.DataSource = cnx.SelectCmd("select * from Attachement where Accidentid='" + id + "'");
listBox1.DisplayMember = "RealFilename";
listBox1.ValueMember = "Filename";
}
}
To delete a File you can use
File.Delete(filePath)
But why don't move it with a single command instead?
File.Move(filePathSource, filePathDestination);
If you can't delete or move a file, you probably still have a Stream open.
Here a working example, how to use an OpenFileDialog and delete and copy the selected file.
using (File.Create(#"c:\Temp\txt.txt")); // File.Create wrapped in a using() to ensure disposing the stream.
using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
File.Copy(ofd.FileName, ofd.FileName + "2.txt");
File.Delete(ofd.FileName);
File.Delete(ofd.FileName + "2.txt");
}
}
Notice, that i wrap a using(...) around the File.Create(). This is because it opens a Stream to the File, which locks it. If you remove the using(...) around the File.Create() the deletion will not work.
To understand why you can't delete your File, you have to search your code for any access to the file.

Why does WriteLine in C# change my format in Text File?

So I'm writing an app and without any problem I was getting streamwriter to write new lines using the WriteLine. However, when I got to a certain textbox it automatically started indenting. Please see below image and code:
This is under a save button
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = #"C:\DR\Desktop\4-22-18";
sfd.RestoreDirectory = true;
sfd.FileName = "G-12";
sfd.Filter = "txt files(*.txt)|*.txt| Word Files | *.doc";
if (sfd.ShowDialog()==DialogResult.OK)
{
Stream fileStream = sfd.OpenFile();
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine(lblDate.Text);
sw.WriteLine(lblTime.Text);
sw.WriteLine("\r");
sw.WriteLine("G-12"+"\t"+ lblNotes.Text + " " + txtNotes.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblSG.Text+" "+ nmSG.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblTinWeight.Text + " " + nmTinWeight.Text);
sw.WriteLine(lblKIO3.Text + " "+ nmKIO3Volume.Text);
sw.WriteLine(lblKIO3N.Text + nmKIO3N.Text);
sw.WriteLine(lblTinPercentage.Text + " "+ lblTinPercent.Text);
sw.WriteLine(lblTinGram.Text + lblTinGrams.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblNeutWeight.Text+nmNeutWeight.Text);
sw.WriteLine(lblNeutVolume.Text+nmNaOHVolume.Text);
sw.WriteLine(lblNeutNormality.Text + nmNaOHNormality.Text);
sw.Close();
}
enter image description here
The text box contains a space. Verify this by looking the value of lblTinWeight.Text (or a different textbox, not sure) in the debugger.

C# - System.IO.IOException

I have a method that saves the text from a text box into a txt file but I get an System.IO.IOException error every time I back out of the SaveFileDialog.
static OpenFileDialog ofd = new OpenFileDialog();
static SaveFileDialog sfd = new SaveFileDialog();
static String cp;
private void SaveClass() {
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK) {
cp = sfd.FileName;
File.Create(cp);
File.WriteAllLines(#cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
}
Visual Studio highlights the code that starts with "File.WriteAllLines" and says that's where I'm getting the error. Thanks.
Exact error message:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\ktfjulien\Documents\poop.txt' because it is being used by another process.
EDIT:
Thank you, I no longer get the error message but everything I save into the text box is written onto one line, regardless if the text is delimited by new lines or not.
You do not need to do File.Create(cp); to write to a file. This is the cause of the error. Instead, directly do:
cp = sfd.FileName;
FileStream fs = File.OpenWrite(cp);
And if you want to use the StreamWriter instead of FileStream, use the FileStream as the input for your StreamWriter
StreamWriter sw = new StreamWriter(fs);
Or, you could also directly use File.WriteAllLines as you show - don't use the File.Create:
if (sfd.ShowDialog() == DialogResult.OK) {
cp = sfd.FileName;
//File.Create(cp); //remove this
File.WriteAllLines(#cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
When you are creating file using File.Create() this file is already used by File.Create() you need close that file before use another place so before writing text to the file close file writer
var file = File.Create(cp);
file.Close();
complete working solution
static OpenFileDialog ofd = new OpenFileDialog();
static SaveFileDialog sfd = new SaveFileDialog();
static String cp;
private void SaveClass()
{
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
cp = sfd.FileName;
var file = File.Create(cp);
file.Close();
File.WriteAllLines(#cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
}
You have no need to create the file, File.WriteAllLines will do it for you (or clear up the file if it exists):
private void SaveClass() {
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
File.WriteAllLines(sfd.FileName, StudentTextBox.Text
.Split(new String[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries));
}

Save text to Exisit file c#

I'am trying to add new text to exist file which i created but when he click save i have always the same save us. Program adding text but i always must create new text.
string text = System.IO.File.ReadAllText(#"D:\test.txt");
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
text = "iNFO ADD" + " = " + textBox3.Text + Environment.NewLine;
File.AppendAllText(saveFileDialog1.FileName, text);
}
}
You can add your text in string[] or List and after that add in text file.
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
List<string> appendLines = new List<string>()
{
"one string",
"two string"
};
File.AppendAllLines(saveFileDialog.FileName, appendLines);
}
}
Change text = to text +=, and also use WriteAllText in case the file is the same as the one you just read in (otherwise you will read in the file, then append the same data back into the file). Currently you are reading a file into the variable text, the immediately overwriting all of that data with new data.
string text = System.IO.File.ReadAllText(#"D:\test.txt");
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
text += "iNFO ADD" + " = " + textBox3.Text + Environment.NewLine;
File.AppendAllText(saveFileDialog1.FileName, text);
}
Or, if you really want to use AppendAllText and simply want to append to an existing file, you actually want to leave your text = unchanged and do this instead (no reason to read in the file):
string fileName = #"D:\test.txt";
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string text = "iNFO ADD" + " = " + textBox3.Text + Environment.NewLine;
File.AppendAllText(fileName, text);
}

C# SaveFileDialog

I am using the savefiledialog to save a file. Now I need to check if the name already exists.
If it exists the user needs to get a chance to change the name or overwrite the already existing file.
I have tried it with everything and searched a lot but can't find a solution while I technically think it should be easy to do. In the if (File.Exists(Convert.ToString(infor)) == true) the check must take place.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = Path.GetDirectoryName(sfd.FileName);
string filename = Path.GetFileNameWithoutExtension(sfd.FileName);
for (int i = 0; i < toSave.Count; i++)
{
FileInfo infor = new FileInfo(path + #"\" + filename + "_" + exportlist[i].name + ".xlsx");
if (File.Exists(Convert.ToString(infor)) == true)
{
}
toSave[i].SaveAs(infor);
MessageBox.Show("Succesvol opgeslagen als: " + infor);
}
}
Just use the OverwritePrompt property of SaveFileDialog:
SaveFileDialog sfd = new SaveFileDialog{ Filter = ".xlsx Files (*.xlsx)|*.xlsx",
OverwritePrompt = true };
MSDN link on OverwritePrompt can be found here.
do this instead
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
sfd.OverwritePrompt = true;
That should do the work for you
I would use an approach like this:
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
do
{
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = Path.GetDirectoryName(sfd.FileName);
string filename = Path.GetFileNameWithoutExtension(sfd.FileName);
try
{
toSave[i].SaveAs(infor);
break;
}
catch (System.IO.IOException)
{
//inform user file exists or that there was another issue saving to that file name and that they'll need to pick another one.
}
}
} while (true);
MessageBox.Show("Succesvol opgeslagen als: " + infor);
Catching an exception instead of using File.Exists is really the only way to do it, because something external could create the file between File.Exists and actually writing it, thus throwing an exception you'd have to handle anyway.
This code will loop and continue to prompt the user until the file is successfully written.

Categories

Resources