2015-11-18 45 views
0

我正在寻找一个函数,它允许我读取文件,如在端口上侦听。只要它找到一条线,它就会调用一个方法(带回调)。并在一个单独的过程。 我使用:异步文件读取像套接字BeginReciefeFrom(...)

BeginRecieveFrom(socket.bytes, 0, BufferSize, SocketFlags.None, ref endpoint, new AsyncCallback(RecieveFromCallback), state); 

我已经有一段搜索,但没有发现任何东西。

+0

您是否想将文件读取为二进制文本或文本? –

回答

0

Stream类支持BeginRead()

下面是一个例子:(读二进制)

// This class will keep reading until all requested byte are read. 
public static class FileReader 
{ 
    public static void ReadBytes(Stream stream, byte[] buffer, int offset, int count, Action complete) 
    { 
     stream.BeginRead(buffer, offset, count, (asyncResult) => 
     { 
      var bytesRead = stream.EndRead(asyncResult); 

      offset += bytesRead; 
      count -= bytesRead; 

      if (count == 0) 
       complete(); 
      else 
       ReadBytes(stream, buffer, offset, count, complete); 

     }, null); 
    } 
} 

byte[] buffer = new byte[65536]; 
var bytesNeeded = buffer.Length; 

var fileStream = new FileStream("filename.ext", FileMode.Open, FileAccess.Read); 

if (bytesNeeded > fileStream.Length) 
    bytesNeeded = (int)fileStream.Length; 

FileReader.ReadBytes(fileStream, buffer, 0, bytesNeeded,() => 
{ 
    Trace.WriteLine("done"); 
}); 

这将会读取直到[count]个字节进行熵。这是一个的例子 ..

+0

最好使用基于任务的异步方法,如[Stream.ReadAsync](https://msdn.microsoft.com/en-us/library/system.io.stream.readasync(v = vs.110).aspx )。代码变得很多* –

+0

同意,但我只是回答这个问题:_“异步文件读取像套接字BeginReciefeFrom(...)”_ –

+0

这看起来像我在找的东西,感谢您的帮助。我正在尝试它。 –

0

你当然可以读取一个文件异步,因为它是一个IO操作。

我认为你在找什么是类似于下面的东西,但请注意,这个例子使用新的异步/等待异步模式。

public class Program 
{ 
    public delegate void NewLineCallback(string lineContent); 

    public static void NewLineReceived(string lineContent) 
    { 
     if (lineContent != null) 
     { 
      Console.WriteLine("New line has been read from the file. Number of chars: {0}. Timestamp: {1}", lineContent.Length, DateTime.Now.ToString("yyyyMMdd-HHmmss.fff")); 
     } 
     else 
     { 
      Console.WriteLine("All the file content have been read. Timestamp: {0}", DateTime.Now.ToString("yyyyMMdd-HHmmss.fff")); 
     } 
    } 

    public static async void ReadFile(NewLineCallback newLineCallback) 
    { 
     StreamReader fileInputStreamReader = new StreamReader(File.OpenRead("c:\\temp\\mytemptextfile.txt")); 

     string newLine; 

     do 
     { 
      newLine = await fileInputStreamReader.ReadLineAsync(); 
      newLineCallback(newLine); 
     } 
     while (newLine != null); 
    } 

    public static void Main(string[] args) 
    { 
     ReadFile(NewLineReceived); 

     Console.ReadLine(); // To wait for the IO operation to complete. 
    } 
}