How does it fix? I checked all good sites, and this is the last way to delete, but it's not working. There is my code, I've no idea, why it's not working, just pops up "else" line.
public Task DownloadWithStream(FileInfo info)
{
return Task.Run(() =>
{
using (Stream stream = info.client.OpenRead(info.FileName))
{
info.MaxProgress = Convert.ToInt64(info.client.ResponseHeaders["Content-Length"]) / 1024 / 1024;
using (FileStream fs = File.Create($@"{info.FolderName}/{Path.GetFileName(info.FileName)}"))
{
int len = 0;
do
{
info.ResetEvent.WaitOne();
byte[] buff = new byte[1024];
len = stream.Read(buff, 0, buff.Length);
fs.Write(buff, 0, len);
info.Progress = len / (double)1024 / (double)1024;
}
while (len > 0);
}
}
});
}
private void btnRename_Click(object sender, RoutedEventArgs e)
{
string filePath = tbTo.Text;
if (File.Exists(filePath))
{
File.Delete(filePath);
//lbOutput.SelectedItems.Remove(lbOutput.SelectedItems);
MessageBox.Show("Folder Deleted");
}
else
{
MessageBox.Show("Folder in not exists");
}
}
CodePudding user response:
Don't execute IO operations like reading/writing file or download streams on a background thread. Instead use the provided async API of FileStream
or Stream
wrappers like StreamWriter
/StreamReader
:
using var fileStream = File.OpenWrite(filePath);
// StreamReader/StreamWriter decorates any Stream
using var streamWriter = new StreamWriter(fileStream);
// Write to the underlying stream asynchronously.
// Far better perfomance then executing synchronous IO operations on a background thread (Task.Run)
await streamWriter.WriteAsync("Some text");
To handle files that are selected by the user always avoid a plain TextBox
or text input in general. This is error prone and provides a bad user experience. It's more conveniet to use a file picker dialog. Such a dialog avoids errors due to typing errors or invalid file paths like nonexistent files.
private void DeleteFile_OnButtonClicked(object sender, EventArgs args)
{
var filePickerDialog = new OpenFileDialog();
if (filePickerDialog.ShowDialog() == true)
{
string fileToDelete = filePickerDialog.FileName;
File.Delete(fileToDelete);
}
}