从远程服务器下载文件

时间:2009-01-26 14:58:57

标签: download text-files

我正在使用C#和控制台应用程序,我正在使用此脚本从远程服务器下载文件。我想添加一些区域。首先,当它写入文件时,它不考虑换行符。这似乎运行一定量的字节,然后转到换行符。我希望它保持与它正在读取的文件相同的格式。其次,我需要下载服务器上有多个.jpg文件。如何使用此脚本下载多个.jpg文件

public static int DownLoadFiles(String remoteUrl, String localFile)
    {
        int bytesProcessed = 0;

        // Assign values to these objects here so that they can
        // be referenced in the finally block
        StreamReader remoteStream = null;
        StreamWriter localStream = null;
        WebResponse response = null;

        // Use a try/catch/finally block as both the WebRequest and Stream
        // classes throw exceptions upon error
        try
        {
            // Create a request for the specified remote file name
            WebRequest request = WebRequest.Create(remoteUrl);
            request.PreAuthenticate = true;
            NetworkCredential credentials = new NetworkCredential("id", "pass");
            request.Credentials = credentials;

            if (request != null)
            {
                // Send the request to the server and retrieve the
                // WebResponse object
                response = request.GetResponse();
                if (response != null)
                {
                    // Once the WebResponse object has been retrieved,
                    // get the stream object associated with the response's data
                    remoteStream = new StreamReader(response.GetResponseStream());

                    // Create the local file
                    localStream = new StreamWriter(File.Create(localFile));

                    // Allocate a 1k buffer
                    char[] buffer = new char[1024];
                    int bytesRead;

                    // Simple do/while loop to read from stream until
                    // no bytes are returned
                    do
                    {
                        // Read data (up to 1k) from the stream
                        bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

                        // Write the data to the local file
                        localStream.WriteLine(buffer, 0, bytesRead);

                        // Increment total bytes processed
                        bytesProcessed += bytesRead;
                    } while (bytesRead > 0);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            // Close the response and streams objects here
            // to make sure they're closed even if an exception
            // is thrown at some point
            if (response != null) response.Close();
            if (remoteStream != null) remoteStream.Close();
            if (localStream != null) localStream.Close();
        }

        // Return total bytes processed to caller.
        return bytesProcessed;

2 个答案:

答案 0 :(得分:4)

为什么不使用WebClient.DownloadDataWebClient.DownloadFile

WebClient client = new WebClient();
client.Credentials = new NetworkCredentials("id", "pass");
client.DownloadFile(remoteUrl, localFile);

顺便说一下,将流复制到另一个流的正确方法并不是你所做的。您根本不应该读入char[],因为在下载二进制文件时可能会遇到编码和行结束问题。 WriteLine方法调用也存在问题。将流内容复制到另一个流的正确方法是:

void CopyStream(Stream destination, Stream source) {
   int count;
   byte[] buffer = new byte[BUFFER_SIZE];
   while( (count = source.Read(buffer, 0, buffer.Length)) > 0)
       destination.Write(buffer, 0, count);
}

WebClient类更容易使用,我建议使用它。

答案 1 :(得分:1)

你在结果文件中获得虚假换行的原因是因为StreamWriter.WriteLine()将它们放在那里。请尝试使用StreamWriter.Write()。

关于下载多个文件,您不能多次运行该函数,并将其传递给您需要的不同文件的URL吗?