2013-07-31 4 views
1

끊임없이 변화하는 텍스트 파일을 읽고 싶습니다.텍스트 파일을 읽고 C#으로 업데이트하십시오.

하지만 첫 번째 문제는 파일 크기가 너무 커서 첫 번째 시간이 응답하지 않는다는 것입니다. 그리고이 텍스트 파일 (txt)이 1 초마다 변경됩니다.

처음으로 파일의 마지막 50 줄만이 호출되지는 않았습니까? 그래서 프로그램은 FileHelpers에게 라이브러리

http://filehelpers.sourceforge.net/example_async.html

+2

파일을 변경하는 동안 파일을 읽을 수있는 확실한 방법이 없다고 생각합니다 ... –

+3

로그 파일 읽기? – DevZer0

+1

변화하는 파일을 읽는 것은 그것이 사용되는 동안 파일을 잠그지 않는 어떤 종류의 읽기 전용 옵션을 사용해야 할 것입니다. 마찬가지로, 로그 파일에 기록 할 수 있어야합니다. 로그 파일을 작성하는 경우 로그를 쓰는 응용 프로그램이 사용 중이므로 변경 권한이 없을 수 있습니다. 마지막으로, 귀하의 질문은 명확하지 않습니다 - 파일을 어떻게 수정 하시겠습니까? – Shaamaan

답변

-1

을 중지하지 않습니다 내가 올바르게 이해했다고 가정하면 파일을 다시 열어 FileStream의 Seek 메서드를 사용할 수 있도록 파일을 다시 열어야한다고 생각합니다.

참조 : http://msdn.microsoft.com/en-us/library/system.io.filestream.seek.aspx

당신은 당신이 파일을 읽고 곳으로 위치를 저장해야하는 파일에서 읽을 때마다. 다른 청크 읽기를 시작하면 seek 메서드를 사용하여 오프셋을 사용하여 읽지 않은 파일의 부분으로 이동합니다.

당신은 너무 오랫동안 그것을 잠금 (함으로써 그것에 쓰기 작업을 차단)하지 않고 덩어리에서 파일을 읽을이 방법

스레드 (또는 타이머 객체)를 수시로 파일에서 읽을 수 있습니다. 청크가 너무 커서 파일을 너무 오래 잠그지 않도록하십시오.

+0

동시에 읽고 쓸 때 동기화 문제가 해결됩니까? 그렇다면 아마도 그 샘플을 우리에게주십시오. OP가 도움이 될 것이라는 보증이 주어지지 않는다면이 간단한 문제를 해결하기 위해 OP로 터널링 할 필요가 없습니다. – Gusdor

+0

OP 또는 다른 프로세스에서 파일을 업데이트했는지 여부는 질문에서 알기 어렵습니다. 나에게 그것은 OP가 다른 프로세스 업데이트로 큰 파일을 읽으려고하는 것 같다. –

1

를 사용하려고 텍스트 파일의 비동기 읽기를 들어

그리고 읽기와 끊임없이 변화하는 추가 된 쉽게 그

...

2

Watch 파일 당신은

static class Program 
{ 
    static long position = 0; 

    /// <summary> 
    /// The main entry point for the application. 
    /// </summary> 
    [STAThread] 
    static void Main() 
    { 
     FileSystemWatcher watcher = new FileSystemWatcher(); 
     watcher.Path = System.Environment.CurrentDirectory; 
     watcher.NotifyFilter = NotifyFilters.LastWrite; 
     watcher.Filter = "data.txt"; // or *.txt for all .txt files. 
     watcher.Changed += new FileSystemEventHandler(OnChanged); 
     watcher.EnableRaisingEvents = true; 

     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 
     Application.Run(new Form1()); 
    } 

    public static void OnChanged(object source, FileSystemEventArgs e) 
    { 
     using (FileStream fileStream = new FileStream("data.txt", FileMode.Open)) 
     { 
      // Using Ron Deijkers answer, skip to the part you din't read. 
      fileStream.Seek(position, SeekOrigin.End); 

      for (int i = 0; i < fileStream.Length; i++) 
      { 
       fileStream.ReadByte(); 
      } 
     } 
    } 
} 
0

이 아마 정확하게 당신이 필요로하는 프로그램의 흐름을 보여주지 않는다. 관심이 있지만, 그것은 당신이 읽는주고 늘 당신의 UI (비동기)를 중지 쓰기 않습니다. 잘하면 당신이 필요로하는 것을 적응시킬 수있을 것입니다.

public class AsyncFileUpdate 
{ 
    object locker = new object(); 
    public FileInfo File { get; private set; } 
    public AsyncFileUpdate(FileInfo file) 
    { 
     File = file; 
    } 

    /// <summary> 
    /// Reads contents of a file asynchronously. 
    /// </summary> 
    /// <returns>A task representing the asynchronous operation</returns> 
    public Task<string> ReadFileAsync() 
    { 
     return Task.Factory.StartNew<string>(() => 
      { 
       lock (locker) 
       { 
        using (var fs = File.OpenRead()) 
        { 
         StreamReader reader = new StreamReader(fs); 
         using (reader) 
         { 
          return reader.ReadToEnd(); 
         } 
        } 
       } 
      }); 
    } 
    /// <summary> 
    /// write file asynchronously 
    /// </summary> 
    /// <param name="content">string to write</param> 
    /// <returns>A task representing the asynchronous operation</returns> 
    public Task WriteFileAsync(string content) 
    { 
     return Task.Factory.StartNew(() => 
     { 
      lock (locker) 
      { 
       using (var fs = File.OpenWrite()) 
       { 
        StreamWriter writer = new StreamWriter(fs); 
        using (writer) 
        { 
         writer.Write(content); 
         writer.Flush(); 
        } 
       } 
      } 
     }); 
    } 
} 

/// <summary> 
/// Demonstrates usage 
/// </summary> 
public class FileOperations 
{ 
    public void ProcessAndUpdateFile(FileInfo file) 
    { 
     AsyncFileUpdate fu = new AsyncFileUpdate(file); ; 
     fu.ReadFileAsync() 
      .ContinueWith(p => Process(p.Result)) 
      .ContinueWith(p => fu.WriteFileAsync(p.Result)); 
    } 

    /// <summary> 
    /// does the processing on the file content 
    /// </summary> 
    /// <param name="content"></param> 
    /// <returns></returns> 
    string Process(string content) 
    { 
     throw new NotImplementedException("you do this bit ;)"); 
    } 
} 

이 모든 Task 사업은 작업 병렬 라이브러리에서입니다 - 병렬 및 비동기 프로그래밍 밖으로 hastle을 복용위한 훌륭한 도구 키트. http://msdn.microsoft.com/en-us/library/dd537608.aspx

참고 : 파일 시스템 액세스는 다소 비싸고 물리적으로 저장 매체로 저하됩니다. 이 파일을 관리하고 있습니까 (작성합니까)? 매 초마다 파일을 업데이트하는 것은 아주 금지됩니다. 검사하는 동안 파일이 바뀌는 것에 대해 걱정이된다면 먼저 파일을 복사해야 할 필요가있을 것입니다.

관련 문제