1

我正在使用 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;
4

2 回答 2

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类更容易使用,我建议改用它。

于 2009-01-26T15:03:56.833 回答
1

结果文件中出现虚假换行符的原因是 StreamWriter.WriteLine() 将它们放在那里。尝试使用 StreamWriter.Write() 代替。

关于下载多个文件,你不能只运行几次函数,将你需要的不同文件的 URL 传递给它吗?

于 2009-01-26T15:02:32.217 回答