1

我是 C# 新手,保存到新文件时遇到了一些问题。我的程序有两个保存选项:保存和另存为。

保存时出现共享冲突错误,但我通过关闭前一个文件流解决了这个问题。但是,我仍然无法弄清楚为什么我的另存为代码给了我一个共享冲突错误。

这是代码:

        // get a file stream from the file chooser
        FileStream file = File.OpenWrite(saveFc.Filename);
        // check to see if the file is Ok
        bool fileOk = file.CanWrite;
        if (fileOk == true)
        {
            // get the filename
            string filename = file.Name;
            // store the filename for later use
            UtilityClass.filename = filename;
            // get the text from textview1
            string text = textview1.Buffer.Text;
            // get a StreamWriter
            StreamWriter writer = File.CreateText(filename);
            // write to the file
            writer.Write(text);
            // close/save the file
            writer.Close();
            file.Close();
        }
    }
    // close the file c

如果你能帮我弄清楚,那将不胜感激。谢谢!

4

1 回答 1

3

You're opening the same file twice:

FileStream file = File.OpenWrite(saveFc.Filename);

And:

string filename = file.Name;
StreamWriter writer = File.CreateText(filename);

Your code could probably be simplified to:

using (var writer = File.CreateText(saveFc.Filename))
{
    // store the filename for later use
    UtilityClass.filename = saveFc.Filename;

    // get the text from textview1
    string text = textview1.Buffer.Text;

    // write the text
    writer.Write(text);
}

If you open the file with CreateText/OpenWrite it will always be writeable (or an exception will be thrown). The using block will automatically close the writer when it exits.

于 2012-06-29T04:29:53.940 回答