我正在尝试确保用户不下载将替换现有下载(相同)文件的文件。因此,我尝试创建YesNo对话框供用户确认。但是,即使该文件夹中没有“sample.xml”,当用户单击“下载”按钮时,仍会显示“YesNo”对话框。我可以知道我在哪里做错了吗?我缺乏编程知识,抱歉,请耐心等待。
我的代码如下:
private void btnDownloadXML2_Click(object sender, EventArgs e)
{
if (@"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml" != null)
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to re-download the file? This will replace the old file!", "Warning", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
using (WebClient client = new WebClient())
{
client.DownloadFile("http://www.lse.co.uk/chat/" + txtSharePriceSymbol.Text.ToString(),
@"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml");
}
MessageBox.Show("Download Completed! File has been placed in the folder sharePriceXML!");
}
else if (dialogResult == DialogResult.No)
{
MessageBox.Show("The file is not downloaded. Your old file remains.");
}
}
else if (@"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml" == null)
{
using (WebClient client = new WebClient())
{
client.DownloadFile("http://www.lse.co.uk/chat/" + txtSharePriceSymbol.Text.ToString(),
@"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml");
}
MessageBox.Show("Download Completed! File has been placed in the folder sharePriceXML!");
}
}
答案 0 :(得分:3)
您正在将文件路径检查为字符串以查看它是否为空...它永远不会为空,因为它具有文件路径。
您需要使用File.Exists()
。而不是:
if (@"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml" != null)
使用此:
if (File.Exists(@"..\..\sharePriceXML\" + txtSharePriceSymbol.Text.ToString() + ".xml"))