Programing

잠그지 않고 텍스트 파일을 어떻게 읽을 수 있습니까?

crosscheck 2020. 9. 19. 09:11
반응형

잠그지 않고 텍스트 파일을 어떻게 읽을 수 있습니까?


Windows 서비스가 간단한 형식의 텍스트 파일에 로그를 작성합니다.

이제 서비스 로그를 읽고 기존 로그와 추가 된 로그를 모두 라이브 뷰로 표시하는 작은 애플리케이션을 만들 것입니다.

문제는 서비스가 새 줄을 추가하기 위해 텍스트 파일을 잠그는 동시에 뷰어 응용 프로그램이 읽기 위해 파일을 잠그는 것입니다.

서비스 코드 :

void WriteInLog(string logFilePath, data)
{
    File.AppendAllText(logFilePath, 
                       string.Format("{0} : {1}\r\n", DateTime.Now, data));
}

뷰어 코드 :

int index = 0;
private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                using (StreamReader sr = new StreamReader(logFilePath))
                {
                    while (sr.Peek() >= 0)  // reading the old data
                    {
                        AddLineToGrid(sr.ReadLine());
                        index++;
                    }
                    sr.Close();
                }

                timer1.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


private void timer1_Tick(object sender, EventArgs e)
        {
            using (StreamReader sr = new StreamReader(logFilePath))
            {
                // skipping the old data, it has read in the Form1_Load event handler
                for (int i = 0; i < index ; i++) 
                    sr.ReadLine();

                while (sr.Peek() >= 0) // reading the live data if exists
                {
                    string str = sr.ReadLine();
                    if (str != null)
                    {
                        AddLineToGrid(str);
                        index++;
                    }
                }
                sr.Close();
            }
        }

내 코드를 읽고 쓰는 데 문제가 있습니까?

문제를 해결하는 방법?


서비스와 판독기 모두 로그 파일을 비 독점적으로 열도록해야합니다. 이 시도:

서비스의 경우 다음과 같이 생성 된 FileStream 인스턴스를 사용합니다.

var outStream = new FileStream(logfileName, FileMode.Open, 
                               FileAccess.Write, FileShare.ReadWrite);

독자의 경우 동일하게 사용하지만 파일 액세스를 변경하십시오.

var inStream = new FileStream(logfileName, FileMode.Open, 
                              FileAccess.Read, FileShare.ReadWrite);

행운을 빕니다!


텍스트 파일을 읽는 동안 공유 모드를 명시 적으로 설정합니다.

using (FileStream fs = new FileStream(logFilePath, 
                                      FileMode.Open, 
                                      FileAccess.Read,    
                                      FileShare.ReadWrite))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        while (sr.Peek() >= 0) // reading the old data
        {
           AddLineToGrid(sr.ReadLine());
           index++;
        }
    }
}

new StreamReader(File.Open(logFilePath, 
                           FileMode.Open, 
                           FileAccess.Read, 
                           FileShare.ReadWrite))

-> 이것은 파일을 잠그지 않습니다.


The problem is when you are writing to the log you are exclusively locking the file down so your StreamReader won't be allowed to open it at all.

You need to try open the file in readonly mode.

using (FileStream fs = new FileStream("myLogFile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        while (!fs.EndOfStream)
        {
            string line = fs.ReadLine();
            // Your code here
        }
    }
}

I remember doing the same thing a couple of years ago. After some google queries i found this:

    FileStream fs = new FileStream(@”c:\test.txt”, 
                                   FileMode.Open, 
                                   FileAccess.Read,        
                                   FileShare.ReadWrite);

i.e. use the FileShare.ReadWrite attribute on FileStream().

(found on Balaji Ramesh's blog)


Have you tried copying the file, then reading it?

Just update the copy whenever big changes are made.


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.

참고URL : https://stackoverflow.com/questions/3448230/how-can-i-read-a-text-file-without-locking-it

반응형