C# Create txt file and save - c#

I am trying to create a file and save text, but it's only creating file can anyone suggest what the problem is?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.FileName = "Password";
sfd.Title = "Save Text File";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
StreamWriter bw = new StreamWriter(File.Create(path));
bw.Write(randomstring);
bw.Dispose();
}
}

You need to call bw.Close() before calling bw.Dispose(). Per the API: "You must call Close to ensure that all data is correctly written out to the underlying stream." (http://msdn.microsoft.com/en-us/library/system.io.streamwriter.close(v=vs.110).aspx)
I'd actually change the code to:
using (StreamWriter bw = new StreamWriter(File.Create(path)))
{
bw.Write(randomstring);
bw.Close();
}
The using block will automatically call Dispose(), whether or not everything completes successfully.

Try and use File.WriteAllText instead
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//...
File.WriteAllText(path, randomstring);
}

bw.Write(randomstring);
bw.Dispose();
You write something, then dispose of the object entirely. Try:
bw.Write(randomstring);
bw.Close();
bw.Dispose();

Per the documentation, you need to call bw.Close() before you dispose of it. Also, you should use using to ensure that all IDisposables are properly disposed of.
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
using (var fs = File.Create(path))
using (StreamWriter bw = new StreamWriter(fs))
{
bw.Write(randomstring);
bw.Close();
}
}
Or just use File.WriteAllText:
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
File.WriteAllText(path, randomstring);
}

Related

OpenFile Dialog Box keeps resources open

After opening a photo in my application using the Openfile Dialog I cannot do anything with the file unless I close my application. I have placed the OpenFile Dialog in a using statement and tried various ways to release resources with no success. How can I release the process to avoid the error message "The process cannot access the file because it is being used by another process?
using (OpenFileDialog GetPhoto = new OpenFileDialog())
{
GetPhoto.Filter = "images | *.jpg";
if (GetPhoto.ShowDialog() == DialogResult.OK)
{
pbPhoto.Image = Image.FromFile(GetPhoto.FileName);
txtPath.Text = GetPhoto.FileName;
txtTitle.Text = System.IO.Path.GetFileNameWithoutExtension(GetPhoto.Fi‌​leName);
//GetPhoto.Dispose(); Tried this
//GetPhoto.Reset(); Tried this
//GC.Collect(): Tried this
}
}
Your problem is not (OpenFileDialog) your problem is for PictureBox
you can use this for load image or if this not works
do this for load image
OpenFileDialog GetPhoto = new OpenFileDialog();
GetPhoto.Filter = "images | *.jpg";
if (GetPhoto.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(path: GetPhoto.FileName,mode: FileMode.Open);
Bitmap bitmap = new Bitmap(fs);
fs.Close(); // End using
fs.Dispose();
pbPhoto.Image = bitmap;
txtPath.Text = GetPhoto.FileName;
txtTitle.Text = System.IO.Path.GetFileNameWithoutExtension(GetPhoto.Fi‌​leName);
}
As stated in the doc for Image.FromFile:
The file remains locked until the Image is disposed.
So you could try to make a copy of the image and then release an original Image:
using (OpenFileDialog GetPhoto = new OpenFileDialog())
{
GetPhoto.Filter = "images | *.jpg";
if (GetPhoto.ShowDialog() == DialogResult.OK)
{
using (var image = Image.FromFile(GetPhoto.FileName))
{
pbPhoto.Image = (Image) image.Clone(); // Make a copy
txtPath.Text = GetPhoto.FileName;
txtTitle.Text = System.IO.Path.GetFileNameWithoutExtension(GetPhoto.Fi‌​leName);
}
}
}
If it not help, you could try to make a copy via the MemoryStream and the Image.FromStream method: System.Drawing.Image to stream C#

Overwriting a text file from RichTextBox

Now if you write the text and click on the save button, OpenFileDialog will appear. If you finish something in the same document and click on the save button again, you need to select the save location again. How to make that when saving the same file you do not need to create a new file each time, and just overwrite the current one? Sorry for my English.
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
}
else
{
}
}
It sure is, you just need to remember the last file path you saved and not display the dialog again the next time around; something like this should help:
void Main()
{
Save();
}
private string _filePath = "";
void Save()
{
var overwrite = false;
if (!string.IsNullOrEmpty(_filePath))
{
var res =
MessageBox.Show("Would you like to overwrite your last saved file?", "Overwrite?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly, false);
if (res == DialogResult.Cancel) return;
if (res == DialogResult.No) overwrite = false;
if (res == DialogResult.Yes) overwrite = true;
}
if (!overwrite)
{
var sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File|*.rtf";
var res = sfd.ShowDialog();
if (res != DialogResult.OK) return;
_filePath = sfd.FileName;
}
// do the richTextBox.SaveFile(_filePath) here.
}
In this example it:
CHECK IF FILE PATH ALREADY SET
IF NOT THEN
ASK USER IF THEY WANT TO OVERWRITE THE LAST FILE
IF CANCEL THEN DON'T SAVE
IF YES THEN SET OVERWRITE TO TRUE
IF NO THEN SET OVERWRITE TO FALSE
END IF
CHECK IF OVERWRITING
IF OVERWRITING THEN
SHOW SAVE FILE DIALOG
IF USER DIDN'T CLICK OK THEN DON'T SAVE
IF USER CLICKED OK, SET THE NEW FILE PATH TO USE
END IF
SAVE THE FILE USING THE NOW-REMEMBERED FILE PATH
Perhaps:
private void SaveButton_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = saveFileDialog1.FileName;
}
}
Example from: http://www.c-sharpcorner.com/uploadfile/mahesh/savefiledialog-in-C-Sharp/
Might help some?
private string filePath = string.Empty;
private void SaveButton_Click(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
byte[] buffer = Encoding.ASCII.GetBytes(richTextBox1.Text);
MemoryStream ms = new MemoryStream(buffer);
//write to file
FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
}
else
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
sfd.OverwritePrompt = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
filePath = sfd.FileName;
}
}
}
you can use sfd.OverwritePrompt = false; property to avoid prompt messagebox if file already exists, is this what you are looking for ?

Save file to specific folder in C# using SaveFileDialog

I need to save a file using SaveFileDialog to a specific folder.
For example, say we want to save in "c:\MyNewFolder". If the folder doesn't exist, create it and save there, or only save there if the folder does exist.
String fileName="";
String date = DateTime.Now.Day+"-"+DateTime.Now.Month+"-"+DateTime.Now.Year;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName,FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.WriteLine(tbName.Text);
sw.WriteLine(tbSummary.Text);
}
}
You can look for
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = "c:\\MyNewFolder";
save.RestoreDirectory = true;
string strPath="c:\MyNewFolder";
if (!Directory.Exists(strPath))
{
Directory.CreateDirectory(strPath);
}
else
{
//Continue your logic and append your file name
}

Saving a file in windows forms

I already could open the save file dialog, but when i run the program and tried to save it, it could, but the file is not there. WHy is that? Here is the code:
_saved = false;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "System File (*.pos) | *.pos";
saveFileDialog1.Title = "Save File As";
saveFileDialog1.ShowDialog();
if (_saved)
{
this.Text = "Database - " + saveFileDialog1.FileName + "";
_filename = saveFileDialog1.FileName;
}
else
{
this.Text = this.Text;
}
Thank you, I appreciate your help.
The FileSaveDialog only gives you the UI to choose the file, once the file was choosen by the user you will get the FileName and is now your responsibility to do whatever is necesary with the FileName, such as storing your data and save it.
You should implement the save action by yourself, here is an example.
if(sf.ShowDialog() == DialogResult.OK)
{
using(var fs = new FileStream(sf.FileName,FileMode.Create))
{
// get bytes from text you want to save
byte [] data =new UTF8Encoding().GetBytes(text);
fs.Write(data,0,data.Length);
fs.Flush();
}
}
sf is saveFileDialog1

how do you save from a savefile dialog in C#?

here is the code I am currently using to open a file using the openfiledialog `
private void openToolStripMenuItem_Click_1(object sender, System.EventArgs e)
{
//opens the openfiledialog and gives the title.
openFileDialog1.Title = "openfile";
//only opens files from the computer that are text or richtext.
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
//gets input from the openfiledialog.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//loads the file and puts the content in the richtextbox.
System.IO.StreamReader sr = new
System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = (sr.ReadToEnd());
sr.Close();` here is the code I am using to save through a savefiledialog `
Stream mystream;
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
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)
{
StreamWriter wText = new StreamWriter(mystream);
wText.Write("");
mystream.Close();
`
It allows me to open text files but I can't save changes nor create my own text file. no errors are shown during run time. Thanks again for the extra help.
The SaveFileDialog doesn't do the actual saving for you; it simply allows the user to specify a file path. You use the file path and then do the heavy lifting with an implementation of the StreamWriter class, something like:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using( Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew) )
using( StreamWriter sw = new TextWriter( s ) )
{
sw.Write( someTextBox.Text );
}
}

Categories