How can I read a text file without locking it?

后端 未结 7 603
梦谈多话
梦谈多话 2020-11-27 02:42

I have a windows service writes its log in a text file in a simple format.

Now, I\'m going to create a small application to read the service\'s log and shows both th

7条回答
  •  误落风尘
    2020-11-27 03:31

    This method will help you to fastest read a text file and without locking it.

    private string ReadFileAndFetchStringInSingleLine(string file)
        {
            StringBuilder sb;
            try
            {
                sb = new StringBuilder();
                using (FileStream fs = File.Open(file, FileMode.Open))
                {
                    using (BufferedStream bs = new BufferedStream(fs))
                    {
                        using (StreamReader sr = new StreamReader(bs))
                        {
                            string str;
                            while ((str = sr.ReadLine()) != null)
                            {
                                sb.Append(str);
                            }
                        }
                    }
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                return "";
            }
        }
    

    Hope this method will help you.

提交回复
热议问题