2013-06-12 25 views
1

我试图从我的机器发送一个文件到浏览器,以便它可以在我正在处理的.NET应用程序中下载。我正在使用this SO答案中的代码,但使用FileWebRequest而不是使用HttpWebRequest,因为我正在访问本地计算机上的文件。请求如下所示: FileWebRequest fileReq = (FileWebRequest)WebRequest.Create(@"file:///C:/Tmp/new.html");当我将url file:///C:/Tmp/new.html复制到浏览器中时,它会给我正确的文件。但是当我在我的代码中使用fileReq.ContentLength时,它总是返回0,这导致我相信该文件由于某种原因而未被读取。谁能告诉我这里发生了什么?FileWebRequest不返回它应该的内容

编辑:这里是我的代码,就像我从另一个SO问题完全一样,但我用FileWebRequest而不是HttpWebRequest。

 Stream stream = null; 
     int bytesToRead = 10000; 
     byte[] buffer = new Byte[bytesToRead]; 
     try 
     {    
      FileWebRequest fileReq = (FileWebRequest)WebRequest.Create(@"file:///C:/Tmp/new.html"); 
      FileWebResponse fileResp = (FileWebResponse)fileReq.GetResponse(); 

      if (fileReq.ContentLength > 0) 
      { 
       fileResp.ContentLength = fileReq.ContentLength; 
       stream = fileResp.GetResponseStream(); 
       var resp = HttpContext.Current.Response; 
       resp.ContentType = "application/octet-stream"; 
       resp.AddHeader("Content-dsiposition", "attachment; filename=" + url); 
       resp.AddHeader("Content-Length", fileResp.ContentLength.ToString()); 

       int length; 
       do 
       { 
        if (resp.IsClientConnected) 
        { 
         length = stream.Read(buffer, 0, bytesToRead); 
         resp.OutputStream.Write(buffer, 0, length); 
         resp.Flush(); 
         buffer = new Byte[bytesToRead]; 
        } 
        else 
        { 
         length = -1; 
        } 
       } while (length > 0); 
      } 
     } 
     catch (Exception ex) 
     { 
      FileLabel.Text = ex.Message.ToString(); 
     } 
     finally 
     { 
      if (stream != null) 
      { 
       stream.Close(); 
      } 
     } 
+0

提供您写下的实际代码。 –

+0

为什么你不打开文件并将其提供给响应?为什么用请求/响应对“打开”它?你有没有考虑过Response.TransmitFile? – Alexander

+0

@Alexander这听起来像我想要做的,你能否详细说明如何做到这一点? – azrosen92

回答

0

尝试WebClient类。

public static void Main (string[] args) 
{ 
    if (args == null || args.Length == 0) 
    { 
     throw new ApplicationException ("Specify the URI of the resource to retrieve."); 
    } 
    WebClient client = new WebClient(); 

    // Add a user agent header in case the 
    // requested URI contains a query. 

    client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 

    Stream data = client.OpenRead (args[0]); 
    StreamReader reader = new StreamReader (data); 
    string s = reader.ReadToEnd(); 
    Console.WriteLine (s); 
    data.Close(); 
    reader.Close(); 

tutorial here