File is being used by another process

后端 未结 7 1242
野的像风
野的像风 2021-01-11 21:08

I have a program that roughly does this:

  1. open a file to read from it.
  2. close the file
  3. Start a filewatcher to watch for changes in the file.
7条回答
  •  生来不讨喜
    2021-01-11 21:38

    Note: even if "file.txt" is open in Notepad, this code still works, because it is opening for read.

    using System;
    using System.IO;
    
    class Program
    {
      static void Main(string[] args)
      {
        ReadFromFile(@"C:\file.txt");
        Console.ReadLine();
      }
    
      static void ReadFromFile(string filename)
      {
        string line;
        using (StreamReader sr = File.OpenText(filename))
        {
          line  = sr.ReadLine();
          while (line != null)
          {
            Console.WriteLine(str);
            line = sr.ReadLine();
          }
          sr.Close();
        }
      }
    }
    

    Or just:

    string text = System.IO.File.ReadAllText(@"C:\file.txt");

提交回复
热议问题