How do I overwrite a file if it already exists? - c#

I'm making a text editor using fastColoredTextbox. I have a button that allows you to save your text onto your pc. The problem is that it throws an exception when the user tries to save the file as a file that already exists, instead of overwriting the file.
This is my code.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(fastColoredTextBox1.Text);
}
}
How would I go about making it overwrite the file if it already exists?

Maybe this could help you:
sw = new StreamWriter(path, true);
sw.WriteLine(line);
https://learn.microsoft.com/es-es/dotnet/api/system.io.streamwriter.-ctor?view=net-6.0#system-io-streamwriter-ctor(system-string-system-boolean)

I changed up my code a bit and ended up going with this, which somehow got it to work.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Stream s = saveFileDialog1.OpenFile();
StreamWriter sw = new StreamWriter(s);
sw.Write(fastColoredTextBox1.Text);
sw.Close();
}

Related

in C#, save multiple files in selected path in saveFileDialog

I am using C# with sliverlight 5. I am using SaveFileDialog to get the userselected file name. Now I need to save multiple files at same location with different extensions. I tried the following
string directory = System.IO.Path.GetDirectoryName(dialog.SafeFileName);
Stream fileStream = dialog.OpenFile();
StreamWriter sw = new StreamWriter(fileStream);
string sequenceFASTAFileNAme = System.IO.Path.GetFileNameWithoutExtension(dialog.SafeFileName) + ".fa";
string path = System.IO.Path.Combine(directory, sequenceFASTAFileNAme);
if (!File.Exists(sequenceFASTAFileNAme))
{
StreamWriter tw = File.AppendText(System.IO.Path.Combine(directory,sequenceFASTAFileNAme));
tw.WriteLine("The next line!");
tw.Flush();
tw.Close();
}
But I am getting following error
File operation not permitted. Access to path 'helo.fa' is denied.
at
StreamWriter tw = File.AppendText(System.IO.Path.Combine(directory,sequenceFASTAFileNAme));
How can I just get the path of the selected file.
private void button1_Click_1(object sender, EventArgs e)
{
string[] FileV = new string[3];
FileV[0] = "val1";
FileV[2] = "val2";
FileV[3] = "val3";
save(FileV);
}
private void save(string[] FileValue)
{
System.IO.Stream myStream;
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)
{
System.IO.StreamWriter tw = System.IO.File.AppendText(saveFileDialog1.FileName + ".ex1");
tw.WriteLine(FileValue[1]);
tw.Flush();
tw.Close();
tw = System.IO.File.AppendText(saveFileDialog1.FileName + ".ex2");
tw.WriteLine(FileValue[2]);
tw.Flush();
tw.Close();
tw = System.IO.File.AppendText(saveFileDialog1.FileName + ".ex3");
tw.WriteLine(FileValue[3]);
tw.Flush();
tw.Close();
myStream.Close();
}
}
}

using open file dialog box on a windows form

I wrote a program which reads a csv file, makes some changes and writes to a new csv file.
I want the user to be able to select the csv file to be read from their directory using an open file dialog box on a windows form.
So far I have been able to write some of the code so that the user can look for the file but I am not sure on how to link the file the user has chosen to the steamreader.
This is the code to read and write the csv file
try
{
using (StreamWriter sw = new StreamWriter("X:/PublishedSoftware/Data/NEWPYAEGON1PENSION.csv"))
{
using (StreamReader sr = new StreamReader(""))
{
This is the code for the open file dialog box
private void btnFindAegonFile_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "csv files(*.csv)|*.csv|All files(*.*)|*.*";
openFileDialog1.FileName = "Browse for the AEGON file.";
DialogResult result = openFileDialog1.ShowDialog();
txtFindAegonFile.Text = this.openFileDialog1.FileName;
If you have the file name:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = this.openFileDialog1.FileName;
...
}
You can read the contents using the stream reader (in the place of ...):
using (StreamReader sr = new StreamReader(fileName))
Or read the contents directly:
string input = File.ReadAllText(fileName);
Here is a snippet of how to go from a file name to a StreamReader:
var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (var sr = new StreamReader(fs))
{
...
}
You have to complete the FileOpen Dialog code snippet by passing the file path to StreamWriter, like:
using (StreamWriter sw = new StreamWriter(fileName));
// ... open the file w/StreaWriter
Use openFileDialog1's FileOK event to know when the user has selected a valid file. You can then recive the file path from openFileDialog1.FileName.
I got it working I used:
string readfilename = txtFindAegonFile.Text;
try
{
using (StreamReader sr = new StreamReader(readfilename))
using (StreamWriter sw = new StreamWriter("X:/PublishedSoftware/Data/NEWPYAEGON1PENSION.csv"))
}

SaveFileDialog existing file

I am using the savefiledialog in C# and I am allowing the user to save an xml node to a file however if the user chooses to create a new file and save the node in it, it works but when the user chooses to save to an existing file then it is overwritten. what I need is that it kind of loads the file and I can append the node in it, Thanks
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.FileName = "untitled"; // Default file name
sfd.DefaultExt = ".xml"; // Default file extension
sfd.Filter = "Xml documents (.xml)|*.xml";
Nullable<bool> result = sfd.ShowDialog();
if (result == true)
{
if (System.IO.Path.GetExtension(sfd.FileName) != ".xml")
{
MessageBox.Show("You can only choose files with .xml extensions");
return;
}
this.save_xml_file(sfd.FileName);
}
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", "no");
doc.AppendChild(docNode);
XmlNode fubiRec = Doc.CreateElement("FubiRecognizers");
XmlAttribute conf = Doc.CreateAttribute("globalMinConfidence");
conf.Value = "0.51";
fubiRec.Attributes.Append(conf);
doc.AppendChild(fubiRec);
XmlAttribute gestureAttribute = doc.CreateAttribute("name");
gestureAttribute.Value = gestureName;
gestureNode.Attributes.Append(gestureAttribute);
fubiRec.AppendChild(gestureNode);
If you use FileStream and StreamWriter then you need to specify your type of Stream first.
FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write);
FileMode.Append will create file if it doesn't exist,and append the one that exists.
Then use it in StreamWriter
StreamWriter sw = new StreamWriter(fileSTream, Encoding.Default);
If you don't use this kind of stream or writer, there is always something similar available.

encrypting a copy of a text file in c# (Windows Forms)

I'm working on an encryption program in C# (Windows Forms) and one of the options I'd like to add is that the user will be able to choose an existing text (.txt) file, and the program would make a new file which is the file chosen, but encrypted (without making any changes in the original file).
I though about making a copy of the original file and then encrypting the new file, but I have no clue how to do it.
Please tell me how to do it.
Thanks a lot in advance!
StreamReader/StreamWriter for loading and saving the file.
StreamReader:
string unencryptedText;
private void ReadTextFile()
{
using (StreamReader reader = new StreamReader("file.txt"))
{
unencryptedText= reader.ReadToEnd();
}
}
StreamWriter
using (StreamWriter writer = new StreamWriter("encryptedFile.txt", true))
{
writer.Write(encryptedText);
}
Encryption: Simple insecure two-way "obfuscation" for C#
Update
Chose Directory where to save encrypted file(only Directory)
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(fbd.SelectedPath+"\\encryptedFile.txt", true))
{
writer.Write(encryptedText);
}
}
Chose Directory and FileName
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(sfd.FileName, true))
{
writer.Write(encryptedText);
}
}
Use System.IO.StreamReader and System.IO.StreamWriter to read and write from text files.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
using (StreamReader sr = new StreamReader(filePath))
{
fileContents = sr.ReadToEnd();
}
string encryptedContents = Encrypt(fileContents);
using (StreamWriter sw = new StreamWriter(destinationPath))
{
sw.Write(encryptedContents);
}
File.Copy(pathX,pathY)
Will copy the file from path X to path Y.
The next thing is to write the encrypted text to the copied file:
File.WriteAllText(pathY,textToWrite)
I can also say you will learn more if you read msdn examples.
Everything you look for is there.

How to save an image to a file in WPF

I am new in wpf control and framework. I cant seem to save my images can you help me
Below is my code
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = System.IO.Path.GetFileNameWithoutExtension(newlist[currentPicture]);
Nullable<bool> result = sfd.ShowDialog();
if (result == true)
{
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(newlist[currentPicture]);
bmp.Save(newlist[currentPicture]);
}
For a System.Drawing.Bitmap, you need to pass the dialog's FileName property to the Save method.
EDIT: In WPF:
var encoder = new PngBitmapEncoder()
encoder.Frames.Add(BitmapFrame.Create(image));
using (var stream = dialog.OpenFile())
encoder.Save(stream);

Categories