警惕使用WebClient.DownloadFile(string uri,string filePath)方法

本文探讨了使用 WebClient.DownloadFile 方法下载文件时可能遇到的问题,特别是当目标文件已存在且下载过程中发生错误时,该方法可能会删除原有文件内容。文章提供了一种替代方案,通过 WebClient 下载字符串内容后再写入文件,从而避免潜在的数据丢失风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

WebClient.DownloadFile(string uri,string filePath)方法用来请求一个url,并将请求内容存到本地的一个文件中。

使用这个方法,如果filePath是一个已经存在的文件,如果DownloadFile的执行web请求的过程中发生了错误,则会删除掉filePath以前的内容。以下是验证代码,和另一种选择方案。

 

class Program
{
    
static void Main(string[] args)
    {
        
const string filePath = @"c:\a.html";
        
const string url = "http://dat0a11.book.hexun.com/chapter-1031-1-7.shtml";
        
try
        {
            
using (WebClient wc = new WebClient())
            {
                
//wc.DownloadFile("http://dat0a11.book.hexun.com/chapter-1031-1-7.shtml", filePath);

                
string html = wc.DownloadString(url);
                
using (StreamWriter writer = new StreamWriter(filePath,false,wc.Encoding))
                {
                    writer.Write(html);
                    writer.Flush();
                }
            }
        }
        
catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.Read();
    }
}
刚刚到第一个窗口更新了:“PS C:\Users\Administrator> # 手动下载安装包 >> $ProgressPreference = 'SilentlyContinue' >> $webClient = New-Object System.Net.WebClient >> >> # 下载 Node.js >> $nodeUrl = "https://nodejs.org/dist/v20.12.1/node-v20.12.1-x64.msi" >> $nodeInstaller = "$env:TEMP\node-installer.msi" >> $webClient.DownloadFile($nodeUrl, $nodeInstaller) >> Start-Process msiexec.exe -Wait -ArgumentList "/i", "`"$nodeInstaller`"", "/quiet", "/norestart" >> >> # 下载 .NET SDK >> $dotnetUrl = "https://download.visualstudio.microsoft.com/download/pr/8d5ffbe0-0e5b-4d9e-84aa-7950d7e2c4bd/dotnet-sdk-8.0.300-win-x64.exe" >> $dotnetInstaller = "$env:TEMP\dotnet-installer.exe" >> $webClient.DownloadFile($dotnetUrl, $dotnetInstaller) >> Start-Process $dotnetInstaller -Wait -ArgumentList "/install", "/quiet", "/norestart" >> >> # 设置环境变量 >> [System.Environment]::SetEnvironmentVariable("PATH", "C:\Program Files\nodejs;C:\Program Files\dotnet;$env:PATH", "Machine") >> $env:PATH = "C:\Program Files\nodejs;C:\Program Files\dotnet;$env:PATH" >> 使用“2”个参数调用“DownloadFile”时发生异常:“远程服务器返回错误: (400) 错误的请求。” 所在位置 行:14 字符: 1 + $webClient.DownloadFile($dotnetUrl, $dotnetInstaller) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException Start-Process : 由于出现以下错误,无法运行此命令: 系统找不到指定的文件。。 所在位置 行:15 字符: 1 + Start-Process $dotnetInstaller -Wait -ArgumentList "/install", "/quie ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Start-Process],InvalidOperationException + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand PS C:\Users\Administrator> Set-ExecutionPolicy RemoteSigned -Scope LocalMachine -Force PS C:\Users\Administrator> cd E:\ PS E:\> .\Setup-Environment.ps1 涓嬭浇 Node.js 瀹夎绋嬪簭... 姝e湪瀹夎 Node.js... 涓嬭浇 .NET SDK 瀹夎绋嬪簭... 澶囩敤涓嬭浇婧? https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-8.0.300-windows-x64-installer 使用“2”个参数调用“DownloadFile”时发生异常:“远程服务器返回错误: (400) 错误的请求。” 所在位置 E:\Setup-Environment.ps1:47 字符: 5 + $webClient.DownloadFile("https://download.visualstudio.microsoft. ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException 姝e湪瀹夎 .NET SDK... Start-Process : 由于出现以下错误,无法运行此命令: 系统找不到指定的文件。。 所在位置 E:\Setup-Environment.ps1:51 字符: 1 + Start-Process $dotnetInstaller -Wait -ArgumentList "/install", "/quie ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Start-Process],InvalidOperationException + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand 璁剧疆绯荤粺鐜鍙橀噺... node : 无法将“node”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确 ,然后再试一次。 所在位置 E:\Setup-Environment.ps1:62 字符: 32 + Write-Host "楠岃瘉 Node.js 瀹夎: $(node --version)" + ~~~~ + CategoryInfo : ObjectNotFound: (node:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 楠岃瘉 Node.js 瀹夎: dotnet : 无法将“dotnet”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径 正确,然后再试一次。 所在位置 E:\Setup-Environment.ps1:63 字符: 33 + Write-Host "楠岃瘉 .NET SDK 瀹夎: $(dotnet --version)" + ~~~~~~ + CategoryInfo : ObjectNotFound: (dotnet:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 楠岃瘉 .NET SDK 瀹夎: 鉁?鐜璁剧疆瀹屾垚 PS E:\> PS E:\> Set-ExecutionPolicy RemoteSigned -Scope LocalMachine -Force PS E:\> cd E:\ PS E:\> .\Setup-Environment.ps1 涓嬭浇 Node.js 瀹夎绋嬪簭...
最新发布
08-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值