场景
现在公司的测试环境一些文本日志不让接触,提供一个网络http服务器让人直接访问,这文件大时,一般10MB一个文件,不在同一局域网,网速限制200K,要等很久,访问很慢。
.Net代码请求文本文件最新内容(类似于tail文件)
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
while (true)
{
//var FileLength = 0L;
//var sPosstion = 0;
int CompletedLength = 0;
var filePath = ConfigurationManager.AppSettings["txtfilepath"].ToString();
Console.WriteLine("网络txt文件路径:{0}", filePath);
var lengthRequest = (HttpWebRequest)HttpWebRequest.Create(filePath);
lengthRequest.Method = "HEAD";//只获取文件头,不获取内容,速度快
var ContentLength = ((HttpWebResponse)lengthRequest.GetResponse()).ContentLength;
try
{
lengthRequest.Abort();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
var getLastLength = Convert.ToInt32(ConfigurationManager.AppSettings["getLastLength"].ToString());
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(filePath);
if (ContentLength > getLastLength)
{
myRequest.AddRange((int)(ContentLength - getLastLength));//设置Range值
}
//向服务器请求,获得服务器的回应数据流
HttpWebResponse webResponse = (HttpWebResponse)myRequest.GetResponse();
//FileLength = webResponse.ContentLength + sPosstion;//文件大小=已下载的+服务器返回的
Stream myStream = webResponse.GetResponseStream();
byte[] btContent = new byte[getLastLength];
//Save();//保存下载信息
if ((CompletedLength = myStream.Read(btContent, 0, getLastLength)) > 0)
{
Console.WriteLine(Encoding.UTF8.GetString(btContent));
// FStream.Write(btContent, 0, CompletedLength);
//DownloadedLength += CompletedLength;
//if (BeStop == true) break;
}
else
{
Console.WriteLine("无内容");
}
//FStream.Close();
myStream.Close();
Console.WriteLine("最后刷新时间:"+DateTime.Now.ToString("yyyy-MM-dd HH:m:ss.fff"));
Console.WriteLine("\r\n---------按任意键刷新----------");
Console.ReadKey();
Console.Clear();
}
}
}
}
config文件配置:
<appSettings>
<add key="txtfilepath" value="http://www.text.com/Info/Info.log"/>
<add key="getLastLength" value="2048"/>
</appSettings>