What's the least invasive way to read a locked file in C# (perhaps in unsafe mode)?

前端 未结 3 600
猫巷女王i
猫巷女王i 2020-11-29 09:22

I need to read a Windows file that may be locked, but I don\'t want to create any kind lock that will prevent other processes from writing to the file.

In addition,

3条回答
  •  盖世英雄少女心
    2020-11-29 09:34

    You can do it without copying the file, see this article:

    The trick is to use FileShare.ReadWrite (from the article):

    private void LoadFile()
    {
        try
        {
            using(FileStream fileStream = new FileStream(
                "logs/myapp.log",
                FileMode.Open,
                FileAccess.Read,
                FileShare.ReadWrite))
            {
                using(StreamReader streamReader = new StreamReader(fileStream))
                {
                    this.textBoxLogs.Text = streamReader.ReadToEnd();
                }
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show("Error loading log file: " + ex.Message);
        }
    } 
    

提交回复
热议问题