Search code examples
c#streamwritersystem.io.file

C# Overwrite text file - nothing is written to file


I have two methods: saveFile and saveAsToFile. The first one is supposed to overwrite the contents of the current, existing file. While the second is supposed to save as a new file (if the current is non-existing or the user just wants to make a copy.)

When I use the saveAsToFile method it works every time. When I use the saveFile method it doesn't write anything. (I DO see the "Saved!" MessageBox, though.)

Here are my methods:

    public void saveFile(string[] inData, string inDataTitle) 
    {
        //This method saves the file
        SaveFileDialog savefile;
        string trueFileName;

        if (isStrArrayNotEmpty(inData)) {
            //Only attempt to save the file if there is anything written in the textArea

            if (f.getDocumentSavedStatus()) {
                if (f.getDocumentChangedStatus()) {
                    savefile = new SaveFileDialog();

                    if (inDataTitle.EndsWith("*")) {
                        //Remove the asterisk from the document name

                        savefile.FileName = inDataTitle.Substring(0, inDataTitle.Length - 1);
                    }
                    else {
                        savefile.FileName = inDataTitle;
                    }

                    StreamWriter sw = new StreamWriter(savefile.FileName, false);
                    foreach (string line in inData) {
                        sw.WriteLine(line);
                    }
                    sw.Flush();
                    if (sw.BaseStream != null)
                        sw.BaseStream.Flush();
                    sw.Close();

                    /*
                    using (StreamWriter sw = new StreamWriter(savefile.FileName, false))
                        foreach (string line in inData) {
                            sw.WriteLine(line);
                        }
                    */

                    f.setDocumentName(string.Empty);
                    trueFileName = Path.GetFileName(savefile.FileName);
                    f.setDocumentName(trueFileName);
                    f.setDocumentSavedStatus(true);
                    f.setDocumentChangedStatus(false);      //Changes saved, status updated

                    MessageBox.Show("Saved!");
                }
            }
            else {
                //If the document hasn't been saved before, send the values to the 'Save As' method

                saveAsToFile(inData, inDataTitle);
            }
        }
    }

    public void saveAsToFile(string[] inData, string inDataTitle) 
    {
        //This method checks if there is anything written in the texArea,
        //if so it prompts the user to save the file to disk (Save As)

        SaveFileDialog savefile;
        string trueFileName;

        if (isStrArrayNotEmpty(inData)) {
            //Only attempt to save the file if there is anything written in the textArea

            savefile = new SaveFileDialog();

            if (inDataTitle.EndsWith("*")) {
                //Remove the asterisk from the document name

                savefile.FileName = inDataTitle.Substring(0, inDataTitle.Length - 1);
            }
            else {
                savefile.FileName = inDataTitle;
            }

            savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

            if (savefile.ShowDialog() == DialogResult.OK) {
                StreamWriter sw = new StreamWriter(savefile.FileName, false);
                foreach (string line in inData) {
                    sw.WriteLine(line);
                }
                sw.Flush();
                if (sw.BaseStream != null)
                    sw.BaseStream.Flush();
                sw.Close();


                /*
                using (StreamWriter sw = new StreamWriter(savefile.FileName))
                    foreach (string line in inData) {
                        sw.WriteLine(line);
                    }
                */

                f.setDocumentName(string.Empty);
                trueFileName = Path.GetFileName(savefile.FileName);
                f.setDocumentName(trueFileName);
                f.setDocumentSavedStatus(true);
                f.setDocumentChangedStatus(false);      //Changes saved, status updated
            }
        }
    }

As you can see by the comments in the code; I tried using using, and then I tried to "manually flush" the streamwriter, but nothing works.

Using saveAsToFile works every time. It overwrites the text file as expected, no problems. While saveFile doesn't write anything to the file. (Leaving it unchanged.)

I tried looking for errors in saveFile by using MessageBox.Show to print the values of savefile.Filename and line in the appropriate places - they all worked as expected, yet nothing is written to the actual text file.

isStrArrayNotEmpty returns true if the string array does not contain any white spaces. getDocumentSavedStatus returns the value of a boolean which tells if the file has been saved before or not (existent / non-existent) getDocumentChangedStatus returns the value of a boolean which tells if the file has been modified or not (asterisk by the end of the file name, indicating that work will be lost if the user shuts down the application.)


Solution

  • Does the inDataTitle parameter include the path of the filename you're trying to save? If not, it's likely saving to a file of the same name but in a different folder.

    After your line:-

    StreamWriter sw = new StreamWriter(savefile.FileName, false);
    

    add the line:-

    MessageBox.Show(((FileStream)(sw.BaseStream)).Name);
    

    and it'll tell you where the file is being saved.