Der Prozess kann nicht auf die Datei zugreifen, da Sie von einem anderen Prozess (Datei wird erstellt, enthält aber nichts)

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)

    }
}
InformationsquelleAutor sunil | 2013-12-23
Schreibe einen Kommentar