无法在c#服务中使用webclient下载文件

时间:2014-04-21 06:41:10

标签: c# download webclient

我创建了一个c#服务来下载文件并将它们存储到系统中的特定位置。我使用的服务帐户是LocalSystem。当作为控制台应用程序运行时,完成下载的相同代码。可能是什么问题?

守则:

class OldDownloader
{
    private static Logger logger = LogManager.GetCurrentClassLogger();

    WebClient webClient;               // for downloading
    Stopwatch sw = new Stopwatch();
    WebSocketClient _client;
    string _downloadLocation;
    string _extractLocation;
    int progressval = 0;
    int _fileNo;
    public DownloadState downloadState = DownloadState.DOWNLOADING;

    public OldDownloader(int fileNo, string downloadLocation, string urlAddress, ref WebSocketClient client,string extractLocation = null )
    {
        _client = client;
        _extractLocation = extractLocation;
        _downloadLocation = downloadLocation;
        downloadState = DownloadState.DOWNLOADING;
        _fileNo = fileNo;


        using (webClient = new WebClient())
        {
            Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("http://" + urlAddress);
            sw.Start();
            webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.2; rv:28.0) Gecko/20100101 Firefox/28.0");
            webClient.Headers.Add("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            webClient.Headers.Add("Accept-Language", "en-US,en;q=0.5");
            webClient.Headers.Add("Accept-Encoding", "gzip, deflate");
            //webClient.Headers.Add("Connection", "keep-alive");


                try
                {
                    //Console.WriteLine("downloading...");

                    logger.Debug(string.Format("Download Progress : {0}", "Starting Download"));
                    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
                    webClient.UseDefaultCredentials = true;
                    WebSocketServer.cancelDownloadEvent += downloadCancel;
                    webClient.DownloadFileAsync(URL, downloadLocation);
                    //Console.WriteLine("async dl started");

                }
                catch (Exception ex)
                {
                    logger.ErrorException(string.Format("Exception occured while downloading from client : {0}",_client.address), ex);
                }


        }
    }
    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        // Reset the stopwatch.
        sw.Reset();

        if (e.Cancelled == true)
        {
            string s = String.Format("p {0} {1} {2}", _fileNo, "e","cancelled");
            logger.Debug(string.Format("Download Progress : {0}", s));
            _client.send(s);
            downloadState = DownloadState.CANCELLED;
        }
        else if (null != e.Error)
        {
            logger.ErrorException("Exception occured while trying to download async:",e.Error);
            downloadState = DownloadState.ERROR;


        }
        else
        {
            string s = String.Format("p {0} {1}", _fileNo, 'c');

            logger.Debug(string.Format("Download Progress : {0}", s));
            _client.send(s);
            if (null != _extractLocation)
            {//ZipFile.ExtractToDirectory(_downloadLocation, _extractLocation);

                logger.Debug(string.Format("Download Progress : {0}", "Extracting"));
                ExtractZipFile(_downloadLocation, null, _extractLocation);

            }

        }

        WebSocketServer.cancelDownloadEvent -= downloadCancel;




    }
    private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        if (progressval < e.ProgressPercentage)
        {
            long currentTime = sw.ElapsedMilliseconds;
            progressval = e.ProgressPercentage;
            string s = String.Format("p {0} {1}", _fileNo, e.ProgressPercentage);
            logger.Debug(string.Format("{0}=> Download Progress : {1}",_client.address, s));
            _client.send(s);
        }
    }

    private void ExtractZipFile(string archiveFilenameIn, string password, string outFolder)
    {
        ZipFile zf = null;
        try
        {
            logger.Debug(string.Format("{0}=> Opening zip file : {1}", _client.address, archiveFilenameIn));

            FileStream fs = File.OpenRead(archiveFilenameIn);
            zf = new ZipFile(fs);
            //TODO: get filesize before extraction <or> extract to tempfolder and then copy to camera 
            if (!String.IsNullOrEmpty(password))
            {
                zf.Password = password;     // AES encrypted entries are handled automatically
            }

            logger.Debug(string.Format("{0}=> Unzipping file : {1}", _client.address, archiveFilenameIn));

            foreach (ZipEntry zipEntry in zf)
            {
                if (!zipEntry.IsFile)
                {
                    continue;           // Ignore directories
                }

                String entryFileName = zipEntry.Name;
                // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                // Optionally match entrynames against a selection list here to skip as desired.
                // The unpacked length is available in the zipEntry.Size property.

                byte[] buffer = new byte[4096];     // 4K is optimum
                Stream zipStream = zf.GetInputStream(zipEntry);

                // Manipulate the output filename here as desired.
                String fullZipToPath = Path.Combine(outFolder, entryFileName);
                string directoryName = Path.GetDirectoryName(fullZipToPath);
                if (directoryName.Length > 0)
                    Directory.CreateDirectory(directoryName);

                // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                // of the file, but does not waste memory.
                // The "using" will close the stream even if an exception occurs.
                using (FileStream streamWriter = File.Create(fullZipToPath))
                {
                    StreamUtils.Copy(zipStream, streamWriter, buffer);
                }
            }

        }
        catch (Exception ex)
        {
            logger.Error(ex);
        }
        finally
        {
            if (zf != null)
            {
                zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                zf.Close(); // Ensure we release resources

            }
            string s = String.Format("p {0} {1}", _fileNo, "extracted");
            logger.Debug(string.Format("Download Progress : {0}", s));
            _client.send(s);
        }
    }

    private void downloadCancel(ref WebSocketClient _client)
    {
        if (_client == this._client)
        {
            logger.Debug("Download Cancelled by user");
            webClient.CancelAsync();
            downloadState = DownloadState.CANCELLED;
        }
    }


}

0 个答案:

没有答案