c#使用静态的saveFileDialog1.文件名字符串在不同的空格中
本文关键字:空格 字符串 文件名 静态 saveFileDialog1 | 更新日期: 2023-09-27 18:09:41
所以我做了很多试验,在谷歌上搜索了很多,在来这里问之前读了很多溢出的问题。
我不是c#专业人员,但我对它有一个基本的了解。
所以我有一个c# Windows窗体应用程序,与我的一个窗体(form2),我卡住了。
这个表单基本上是一个UPDATER表单,它读取我的网站上的XML文件(使用XMLTextReader),检查应用程序的新版本,如果有一个它下载它(与一个完整的已经工作的WebClient)。
我知道这可能不是最好的检查更新的方式,如果有很多人下载更新一次,它会搞砸,但这是一个私人应用程序只使用我的朋友和我自己。
所以我所做的是我做了字符串(下载路径)和(SAVEPath)。SAVEPath是saveFileDialog1。文件名和DOWNLOADPath是我的xml文件中的下载链接。
我不确定这是否正确/安全,但我使这些字符串可以在它们的void之外访问,所以我使用:"string SAVEPath {get;设置;}"answers"string DOWNLOADPath {get;设置;}"。
这在我做的每个测试中都工作得很好,我没有遇到任何问题,但是我遇到的一个问题是,当下载开始时,如果用户取消,我可以很好地取消这个过程,但是我不能删除它已经下载了1/2的文件,我需要删除这个文件,因为如果它只下载了一半,文件就会损坏。
当我使用以下命令时:
if (e.Cancelled == true)
{
MessageBox.Show("Download has been canceled.");
//Need to delete the file as if user cancels, the file will only be partially downloaded.
if (File.Exists(SAVEPath))
{
File.Delete(SAVEPath);
}
}
和这粗不工作,因为文件路径不再存在于字符串中,所以有一种方法使SAVEPath得到saveFileDialog1.FileName?
下面是我的代码:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//Need the below to be able to download
using System.Diagnostics;
using System.IO;
using System.Net;
//Need below to access XML
using System.Xml;
//Need the below to add sound
using System.Media;
namespace Downloader
{
public partial class Download : Form
{
WebClient webClient; // WebClient that will be doing the update downloading.
Stopwatch sw = new Stopwatch(); // The stopwatch which used to calculate the download speed
public Download()
{
InitializeComponent();
button1.Enabled = false;
button2.Enabled = false;
}
//Check for update file, after form is shown.
string DOWNLOADPath { get; set; }
private void Form1_Shown(Object sender, EventArgs e)
{
string downloadUrl = "";
Version newVersion = null;
string xmlUrl = "http://mywebsite/Update.xml";
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xmlUrl);
//dont read uneccasary lines, skip to main content in file
reader.MoveToContent();
//store element name
string elementName = "";
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "DoWnloadTest"))
{
while (reader.Read())
{
//if i find element node, store the name for later use.
if (reader.NodeType == XmlNodeType.Element)
{
elementName = reader.Name;
}
else
{
//The text inside the xml if not empty txt file
if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue))
{
//switch to element name.
switch (elementName)
{
case "version":
newVersion = new Version(reader.Value);
break;
case "url":
downloadUrl = reader.Value;
DOWNLOADPath = downloadUrl;
break;
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (reader != null)
reader.Close();
}
label1.Text = "Current version: v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version + ".";
label2.Text = "Newest version: v" + newVersion + ".";
Version applicationVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (applicationVersion.CompareTo(newVersion) < 0)
{
downloadVersionLabel.Text = "Status: Version" + newVersion.Major + "." + newVersion.Minor + "." + newVersion.Build + "." + newVersion.Revision + " of '" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + "' is available, would you like to download it?";
button1.Enabled = true;
}
else
{
downloadVersionLabel.Text = "Status: Your version of '" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + "' is up to date.";
button1.Enabled = false;
button2.Enabled = false;
}
}
public void DownloadFile(string urlAddress, string location)
{
using (webClient = new WebClient())
{
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
// The variable that will be holding the url address (making sure it starts with http://)
Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("http://" + urlAddress);
// Start the stopwatch which we will be using to calculate the download speed
sw.Start();
//Disable the start button, don't want client accidently downloading multiple files
button1.Enabled = false;
button2.Enabled = true;
try
{
// Start downloading the file
webClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
// The event that will fire whenever the progress of the WebClient is changed
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// Calculate download speed and output it to labelSpeed.
labelSpeed.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
// Update the progressbar percentage only when the value is not the same.
progressBar.Value = e.ProgressPercentage;
// Show the percentage on our label.
labelPerc.Text = e.ProgressPercentage.ToString() + "%";
// Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading
labelDownloaded.Text = string.Format("{0} MB's / {1} MB's",
(e.BytesReceived / 1024d / 1024d).ToString("0.00"),
(e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
}
// The event that will trigger when the WebClient is completed
public void Completed(object sender, AsyncCompletedEventArgs e)
{
//Enable the start button
button1.Enabled = false;
button2.Enabled = false;
//Reset the stopwatch.
sw.Reset();
//Change the labels back to 0.
labelDownloaded.Text = "0 MB's / 0 MB's";
labelPerc.Text = "0%";
labelSpeed.Text = "0 kb/s";
//Set progressbar percentage back to 0.
progressBar.Value = 0;
if (e.Cancelled == true)
{
MessageBox.Show("Download has been canceled.");
//Need to delete the file as if user cancels, the file will only be partially downloaded.
if (File.Exists(SAVEPath))
{
File.Delete(SAVEPath);
}
}
else
{
MessageBox.Show("Download complete, newest version is located at: " + Environment.NewLine + "'" + SAVEPath + "'.");
}
}
string SAVEPath { get; set; }
private void button1_Click(object sender, EventArgs e)
{
//Creates a new instance of the SaveFileDialog and Show it.
SaveFileDialog saveFileDialogUPDATE = new SaveFileDialog();
saveFileDialogUPDATE.Filter = "Application (*.exe)|*.exe";
saveFileDialogUPDATE.Title = "Update Test - UPDATE: Please select where to save the newest version.";
saveFileDialogUPDATE.FileName = "Update";
if (saveFileDialogUPDATE.ShowDialog() == DialogResult.OK)
{
//Make the user(s) chosen saving location a string.
string SAVEPath = saveFileDialogUPDATE.FileName;
// If the saveFileDialogUPDATE name is not an empty string use it for saving and do "DownloadFile".
if (SAVEPath != "")
{
DownloadFile(DOWNLOADPath, SAVEPath);
}
else
{
MessageBox.Show("Error: You need to specify where to save the update.");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
if (this.webClient != null)
{
this.webClient.CancelAsync();
}
}
}
}
目前这一行:
string SAVEPath = saveFileDialogUPDATE.FileName;
创建一个局部变量,碰巧与您的SAVEPath
属性具有相同的名称。
我怀疑你的意图是设置你的属性:
SAVEPath = saveFileDialogUPDATE.FileName;
然后文件名可以从其他方法访问