该进程无法访问该文件,因为它正由另一个进程使用(文件已创建但不包含任何内容)

问题描述 投票:9回答:4
using System.IO;

class test
{
    public static void Main()
    {

        string path=@"c:\mytext.txt";

        if(File.Exists(path))
        {
            File.Delete(path);
        }


        FileStream fs=new FileStream(path,FileMode.OpenOrCreate);
        StreamWriter str=new StreamWriter(fs);
        str.BaseStream.Seek(0,SeekOrigin.End); 
        str.Write("mytext.txt.........................");
        str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
        string addtext="this line is added"+Environment.NewLine;
        File.AppendAllText(path,addtext);  //Exception occurrs ??????????
        string readtext=File.ReadAllText(path);
        Console.WriteLine(readtext);
        str.Flush();
        str.Close();

        Console.ReadKey();
  //System.IO.IOException: The process cannot access the file 'c:\mytext.txt' because it is //being used by another process.
  // at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

    }
}
c# file-io exception-handling append .net
4个回答
15
投票

试试这个

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.Write("mytext.txt.........................");
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
                  DateTime.Now.ToLongDateString());
    string addtext = "this line is added" + Environment.NewLine;
    str.Flush();
    str.Close();
    fs.Close();
    // Close the Stream then Individually you can access the file.
}

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3

Console.WriteLine(readtext);

在每个文件操作中,文件将被打开,并且必须在打开之前关闭。在操作1中,您必须关闭文件流以进行进一步操作。


4
投票

您在关闭文件流之前写入文件:

using(FileStream fs=new FileStream(path,FileMode.OpenOrCreate))
using (StreamWriter str=new StreamWriter(fs))
{
   str.BaseStream.Seek(0,SeekOrigin.End); 
   str.Write("mytext.txt.........................");
   str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
   string addtext="this line is added"+Environment.NewLine;

   str.Flush();

}

File.AppendAllText(path,addtext);  //Exception occurrs ??????????
string readtext=File.ReadAllText(path);
Console.WriteLine(readtext);

上面的代码应该可以使用您当前使用的方法。您还应该查看using语句并将您的流包装在using块中。


2
投票

File.AppendAllText不知道您打开的流,因此将在内部尝试再次打开该文件。因为您的流阻止访问该文件,File.AppendAllText将失败,抛出您看到的异常。

我建议您使用str.Writestr.WriteLine,因为您已在代码中的其他地方使用过。

您的文件已创建但不包含任何内容,因为在调用str.Flush()str.Close()之前会抛出异常。


-1
投票
using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
    sw.WriteLine(message);
}
© www.soinside.com 2019 - 2024. All rights reserved.