在保存期间与Ubuntu Linux上共享冲突

时间:2012-06-29 04:14:49

标签: c# linux io save

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

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

以下是代码:

        // 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

如果你能帮助我弄明白,那将非常感激。谢谢!

1 个答案:

答案 0 :(得分:3)

您打开两次相同的文件:

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

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

您的代码可能会简化为:

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);
}

如果使用CreateText / OpenWrite打开文件,它将始终可写(或者将抛出异常)。 using块会在退出时自动关闭writer