无法使用c#服务中的webclient下载文件
我已经创建了一个c#服务来下载文件并将其存储到系统中的特定位置。我使用的服务帐户是LocalSystem。当作为控制台应用程序运行时,下载相同的代码位可以完美地工作。有什么问题吗 守则:无法使用c#服务中的webclient下载文件,c#,download,webclient,C#,Download,Webclient,我已经创建了一个c#服务来下载文件并将其存储到系统中的特定位置。我使用的服务帐户是LocalSystem。当作为控制台应用程序运行时,下载相同的代码位可以完美地工作。有什么问题吗 守则: class OldDownloader { private static Logger logger = LogManager.GetCurrentClassLogger(); WebClient webClient; // for downloading
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;
}
}
}
classoldDownloader
{
私有静态记录器Logger=LogManager.GetCurrentClassLogger();
WebClient WebClient;//用于下载
秒表sw=新秒表();
WebSocketClient \u客户端;
字符串\u下载位置;
字符串提取位置;
int progressval=0;
国际文件号;
public DownloadState DownloadState=DownloadState.DOWNLOADING;
public OldDownloader(int fileNo,string downloadLocation,string urlAddress,ref WebSocketClient client,string extractLocation=null)
{
_客户=客户;
_提取位置=提取位置;
_downloadLocation=下载位置;
downloadState=downloadState.DOWNLOADING;
_fileNo=fileNo;
使用(webClient=newWebClient())
{
Uri URL=urlAddress.StartWith(“http://”,StringComparison.OrdinalIgnoreCase)?新Uri(urlAddress):新Uri(“http://”+urlAddress);
sw.Start();
webClient.Headers.Add(“用户代理”、“Mozilla/5.0(WindowsNT6.2;rv:28.0)Gecko/20100101 Firefox/28.0”);
Add(“Accept”,“text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8”);
webClient.Headers.Add(“接受语言”,“en-US,en;q=0.5”);
添加(“接受编码”、“gzip、deflate”);
//webClient.Headers.Add(“连接”,“保持活动”);
尝试
{
//Console.WriteLine(“下载…”);
Debug(string.Format(“下载进度:{0}”,“开始下载”);
webClient.DownloadFileCompleted+=新的AsyncCompletedEventHandler(已完成);
webClient.DownloadProgressChanged+=新的DownloadProgressChangedEventHandler(ProgressChanged);
webClient.UseDefaultCredentials=true;
WebSocketServer.cancelDownloadEvent+=下载取消;
webClient.DownloadFileAsync(URL,downloadLocation);
//WriteLine(“异步dl启动”);
}
捕获(例外情况除外)
{
ErrorException(string.Format(“从客户端下载时发生异常:{0}”,_client.address),例如);
}
}
}
私有无效已完成(对象发送方,AsyncCompletedEventArgs e)
{
//重新设置秒表。
sw.Reset();
如果(e.Cancelled==true)
{
strings=string.Format(“p{0}{1}{2}”,_fileNo,“e”,“cancelled”);
Debug(string.Format(“下载进度:{0}”,s));
_客户端。发送;
downloadState=downloadState.CANCELLED;
}
else if(null!=e.Error)
{
logger.ErrorException(“尝试下载异步时发生异常:”,e.Error);
downloadState=downloadState.ERROR;
}
其他的
{
strings=string.Format(“p{0}{1}”,_fileNo,'c');
Debug(string.Format(“下载进度:{0}”,s));
_客户端。发送;
如果(空!=\u提取位置)
{//ZipFile.ExtractToDirectory(_downloadLocation,_extractLocation);
Debug(string.Format(“下载进度:{0}”,“提取”);
ExtractZipFile(_downloadLocation,null,_extractLocation);
}
}
WebSocketServer.cancelDownloadEvent-=下载取消;
}
私有void ProgressChanged(对象发送方,下载progresschangedeventargs e)
{
如果(progressval下载进度:{1}”,_client.address,s));
_客户端。发送;
}
}
私有void ExtractZipFile(字符串archiveFilenameIn、字符串密码、字符串outFolder)
{
ZipFile zf=null;
尝试
{
Debug(string.Format(“{0}=>打开zip文件:{1}”,_client.address,archiveFilenameIn));
FileStream fs=File.OpenRead(archiveFilenameIn);
zf=新ZipFile(fs);
//TODO:提取前获取文件大小提取到tempfolder,然后复制到camera
如果(!String.IsNullOrEmpty(密码))
{
zf.Password=Password;//自动处理AES加密的条目
}
Debug(string.Format(“{0}=>解压缩文件:{1}”,_client.address,archiveFilenameIn));
foreach(ZipEntry ZipEntry在zf中)
{
如果(!zipEntry.IsFile)
{
continue;//忽略目录
}
String entryFileName=zipEntry.Name;
//要从条目中删除文件夹:-entryFileName=Path.GetFileName(entryFileName);
//(可选)将EntryName与此处的选择列表匹配,以便根据需要跳过。
//解包长度在zipEntry.Size属性中可用。
byte[]buffer=新字节[4096];//4K是最佳值
流zipStream=zf.GetInputStream(zipEntry);
//根据需要在此处操作输出文件名。
字符串fullZipToPath=Path.Combine(outFolder,entryFileName);
字符串directoryName=Path.GetDirectoryName(fullZipToPath);
如果(directoryName.Length>0)
迪尔