在C#中使用Streams

时间:2011-01-19 19:28:43

标签: c# http

我有兴趣从在线的.txt文件中提取文件。

txt文件存储:

文件名 md5哈希 文件名 md5哈希

我有兴趣从在线获取数据,然后将数据与本地文件进行比较。

        byte[] buffer = new byte[512];
        WebRequest test = WebRequest.Create("http://www.domain.com/file.txt");
        Stream something = test.GetRequestStream();
        something.Read(buffer,0,20);

我不太了解流,以及如何从文件中只读一行。我不想先下载文件然后检索数据。我有兴趣从网上拉它。使用StreamWriter和StreamReader,“流”与普通IO有何不同?

编辑 -

       WebRequest myWebRequest = WebRequest.Create("http://www.domain.com/file.txt");

       WebResponse myReponse = myWebRequest.GetResponse();

       Stream recStream = myReponse.GetResponseStream();

       StreamReader reader = new StreamReader(recStream);

       txt_status.Text = reader.ReadLine();

3 个答案:

答案 0 :(得分:2)

如果您正在阅读文字,请尝试使用TextReader

WebRequest test = WebRequest.Create("http://www.domain.com/file.txt");
Stream something = test.GetRequestStream();
TextReader reader = (TextReader)new StreamReader(something);
string textfile = reader.ReadToEnd();

答案 1 :(得分:2)

GetRequestStream提供了一个用于写入的流。如果您希望返回的数据可以使用GetResponseStream

...

Stream ReceiveStream = myWebResponse.GetResponseStream();

    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

        // Pipe the stream to a higher level stream reader with the required encoding format. 
     StreamReader readStream = new StreamReader( ReceiveStream, encode );
     Console.WriteLine("\nResponse stream received");
     Char[] read = new Char[256];

        // Read 256 charcters at a time.    
     int count = readStream.Read( read, 0, 256 );
        Console.WriteLine("HTML...\r\n");

    while (count > 0) 
    {
            // Dump the 256 characters on a string and display the string onto the console.
        String str = new String(read, 0, count);
        Console.Write(str);
        count = readStream.Read(read, 0, 256);
    }

...

答案 2 :(得分:0)

所有流都是一个字节序列。 MemoryStreams,FileStream等都继承自System.IO.Stream

如果您只是尝试将MD5与本地文件进行比较,您可以执行以下操作(未经测试):

// Download File
WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData();

MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] hash = md5.ComputeHash(bytes);

StringBuilder onlineFile = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
   onlineFile.Append(hash[i].ToString("X2"));
}

// Load Local File
FileStream fs = new FileStream(@"c:\yourfile.txt",FileMode.Open);
byte[] fileBytes = new byte[fs.Length];
fs.Read(fileBytes, 0, fileBytes.Length);

byte[] hash = md5.ComputeHash(fileBytes);

StringBuilder localFile = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
   onlineFile.Append(hash[i].ToString("X2"));
}


if(localFile.ToString() == onlineFile.ToString())
{
   // Match
}