简体   繁体   English

.NET 内核 - 对文本文件进行多个读/写操作

[英].NET Core - Multiple read/write operations on a text file

Multiple read/write operation are access a single file, and while write operation I'm facing this issue多个读/写操作是访问一个文件,而写操作我面临这个问题

The process cannot access the file because it is being used in another process

Using this to add text to file使用它向文件添加文本

using (StreamWriter writer=System.IO.File.AppendText("wwwroot/Files/file.txt"))
      {
           writer.WriteLine(stringData.ToString());
           writer.Close();
      }

Is there anyway to perform multiple read/write on a file?无论如何要对文件执行多次读/写?

Thanks谢谢

Try the below code.试试下面的代码。 You may not need a StreamWriter for this为此,您可能不需要 StreamWriter

        // To append text to file
        System.IO.File.AppendAllText("FilePath", "TextToWrite");

        // To read all text from file
        string textFromFile = System.IO.File.ReadAllText("FilePath");

If are using the same code from multiple threads or apps writing to the same file, you may find when one thread is wiring it finds the file already in use.如果使用来自多个线程的相同代码或写入同一文件的应用程序,您可能会发现当一个线程正在连接时,它会发现该文件已在使用中。 The only reason for the error message is that the file is not closed.错误消息的唯一原因是文件未关闭。

If the calls to write to the file are sequential from the same app then the file is not getting closed properly.如果写入文件的调用是来自同一个应用程序的连续调用,则文件没有正确关闭。

One way to handle this is to check for locked files and retry later.处理此问题的一种方法是检查锁定的文件并稍后重试。 something like this can be used to check if the file is open:像这样的东西可以用来检查文件是否打开:

public static bool CanBeOpenedForExclusiveRead(string filename)
        {
            try
            {
                // Test file for exclusive read/write
                using (System.IO.FileStream fileStream = System.IO.File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    fileStream.Close();
                }
                return true;
            }
            catch
            {
            }

            return false;
        }

if you are already using something like NLog is to use nlog to "log" writes to a file, where nlog will have better handling of these issues across threads.如果您已经在使用 NLog 之类的东西,则使用 nlog 将写入“记录”到文件中,其中 nlog 将更好地跨线程处理这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM