Click here to Skip to main content
15,890,946 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm going to launch a code editor for people to create bots to disagree, it's almost all ready, but what I need help is when saving the file

What I have tried:

I created a function that saves but when the file already exists the person have to replace, then I created a String called currentFile that will store the path of the selected file, then how do I make it just replace the text inside the file without needing to replace the file or open the save menu?

C#
String currentFile = "C:\\Program Files (x86)\\EXAMPLE\\FILE.js";
SaveFileDialog sfd = default(SaveFileDialog);
            if (fctb_code.Text.Length > 0)
            {
                sfd = new SaveFileDialog();

                sfd.ShowDialog();


                string location = currentFile;
                string sourcecode = fctb_code.Text;
                location = sfd.FileName;
                if (!object.ReferenceEquals(sfd.FileName, ""))
                {
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(location, false))
                    {
                        writer.Write(sourcecode);
                        writer.Dispose();
                    }
                }
Posted
Updated 28-Dec-21 14:29pm
Comments
Richard MacCutchan 29-Dec-21 4:39am    
Don't write directly into C:\Program Files (x86); it is a system protected location. Also do not directly overwite an existing file. If your application writes garbage or otherwise fails then the original content is lost. Always create a new file and write to that, then rename it when you are sure that everything worked correctly.

1 solution

File.WriteAllText Method (System.IO) | Microsoft Docs[^] creates or overwrites, and does it all in a single line of code. It will fail if the file already exists and is already open for writing by some process.

BTW: using a Stream isn't useful when you intend to write all the data in a single Write operation...

:)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900