简体   繁体   English

C#从URL读取文件信息

[英]C# Read file info from URL

In my ASP.NET MVC application I'm reading an external file from URL and saving it into a directory on my server. 在我的ASP.NET MVC应用程序中,我正在从URL读取外部文件并将其保存到我服务器上的目录中。 I do this in a loop for every few seconds to have actual data if the file was modified. 如果文件被修改,我每隔几秒钟就会循环一次,以获得实际数据。

What I need is to recognize that the LastWrittenTime of the file accessed via the URL is different from file already downloaded to the server. 我需要知道通过URL访问的文件的LastWrittenTime与已经下载到服务器的文件不同。 I cannot use FileInfo class because "URI formats are not supported". 我不能使用FileInfo类,因为“不支持URI格式”。

So how do I get the last written time of the file from the URL without needing to download the full file for every loop? 那么如何从URL获取文件的最后写入时间而无需为每个循环下载完整文件?

Assuming your HTTP Server allows this. 假设你的HTTP服务器允许这样做。

System.Net.WebRequest req = System.Net.HttpWebRequest.Create("http:\\your\url.ext");
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
    DateTime LastModified;
    if(DateTime.TryParse(resp.Headers.Get("Last-Modified"), out LastModified))
    { 
        //Check if date is good and then go to full download method.
    }
}

When this method doesn't work because the server doesn't allow it. 当此方法不起作用,因为服务器不允许它。 Then the only way of doing this is by fully downloading the file. 然后,唯一的方法是完全下载文件。

I'm afraid you can't. 我怕你不能。

When it's a webpage you want to download, you might hope that the server would set the LastModified attribute of a WebResponse correctly to get the date the page was last modified. 如果它是您要下载的网页,您可能希望服务器正确设置WebResponseLastModified属性以获取上次修改页面的日期。 But even this is not something you can always rely on. 但即使这不是你总能依赖的东西。

When it's a file, there's no way to tell the date unless you saved the file on your own disk. 当它是文件时,除非您将文件保存在自己的磁盘上,否则无法告知日期。 (Like you are doing now.) And even then, depending on server settings, you might be getting the date the file was created on your disc, not on the server you're downloading from. (就像你现在正在做的那样。)即使这样,根据服务器设置,你可能会得到光盘上创建文件的日期,而不是你正在下载的服务器上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM