I guess its just a banality and pretty easy to fix, I'm getting really frustrated these days as whenever I find an idea to build I always face some kind of problem either something in the UI department or this for an example.
I try to download a file thru WebClient, I got a simple UI lined up with two labels, two textfields, one button, a savefiledialog widget. When I try to save the file 开发者_如何转开发I've typed into the first textfield1 and ofcourse push the button to activate the event, I get a webexception, "App cannot access the file as it is used by another process", but heres the deal, I'm telling my app to create the file, save the content of the file from the web into the new file.
You read further from the code provided below: By the way I'm not getting anything from the Debug, I think that's odd. Do I have to break into the breakpoint, as I assumed that a breakpoint would break at the end of the line?
Thanks in advance.private void button1_Click(object sender, EventArgs e)
{
string path = saveFileDialog1.FileName;
if (textBox2.Text != "")
{
string fileExt = textBox2.Text.Substring(textBox2.Text.LastIndexOf('.'));
saveFileDialog1.Filter = String.Format("fileExt | *{0}",fileExt);
// http://code.jquery.com/jquery-1.6.1.min.js
string fileName = textBox2.Text.Substring(textBox2.Text.LastIndexOf('/')+1);
saveFileDialog1.FileName = fileName;
DialogResult dResul = saveFileDialog1.ShowDialog();
if (dResul == DialogResult.OK)
{
Debug.WriteLine(client.ResponseHeaders);
//client.UseDefaultCredentials = NetworkCredential;
//client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
textBox1.Text = Path.Combine(saveFileDialog1.FileName);
//client.DownloadFileAsync(new Uri(textBox1.Text), saveFileDialog1.FileName);
path = saveFileDialog1.FileName;
Debug.WriteLine(client.ResponseHeaders);
client.DownloadFile(textBox1.Text, Path.Combine(path));
}
}
}
Check that code in client_DownloadFileCompleted does not try to access the file.
DownloadFileCompleted event supposed to be used with DownloadFileAsync method, no reason to use events together with blocking methods (DownloadFile).
try this :
remove the textbox2
replace your code by
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
return;
}
string extention = Path.GetExtension(textBox1.Text);
string fileName = Path.GetFileNameWithoutExtension(textBox1.Text);
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = String.Format("{0} files | *{0}", extention);
saveFileDialog.FileName = fileName;
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
WebClient client = new WebClient();
client.DownloadFile(textBox1.Text, saveFileDialog.FileName);
}
}
in textbox1, put the url of the file you want to download
精彩评论