I'm using the following code to download a file and verify if the download succeeded:
try
{
UpdateAvailable = false;
Downloading = true;
using (var webclient = new WebClient { CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore) })
{
var file = Path.Combine(basePath, filename);
await webclient.DownloadFileTaskAsync(updaterexe_fileurl, Path.Combine(basePath, updaterexe_filename));
await webclient.DownloadFileTaskAsync(updatefileurl, file);
}
if (!File.Exists(filename))
{
Error = "Error downloading update. Please try again.";
Log.Error("Error downloading update. Please try again (file does not exist).");
}
else
{
DownloadReady = true;
}
}
catch (Exception ex)
{
Log.Error("Error downloading update: " + ex);
Error = ex.Message;
}
finally
{
Downloading = false;
}
This works in most cases. But I got multiple reports from end-users that sometimes they get the 'try again' error message.
How is this even possible? Clearly, WebClient didn't throw an exception, but it also failed to download the file (it did not exist on disk).
Is this a caching issue? Am I missing any other error handling?
If it's a disk caching issue, I thought about adding the following:
int count = 0;
while (count < 3 || !File.Exists(filename))
{
Thread.Sleep(1000);
count++;
}
But this feels very hacky.
Any ideas?
You download to file, which is Path.Combine(basePath, filename) but you never check to see whether file exists, you check to see whether filename exists.
If basePath and the current working directory differ, the file "won't exist".
Related
These are my troubles: When uploading from any other file location this works. However if I try to upload these files, I can't seem to get past the error.
C:\Users\User\OneDrive - TEAM\2021\Libra\Doc. complete contract TEST - Client 17-06-2021.pdf
C:\Users\User\OneDrive - TEAM\Client\2021\doc12719720210701124854 complete contract.pdf
I can't seem to notice any illegal characthers here ... Please help.
The function:
{
if (file != null && file.ContentLength > 0)
{
var path = Path.Combine(Server.MapPath("~/Files/"), file.FileName);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
try
{
file.SaveAs(path);
}
catch (Exception ex)
{
Log.LogError(string.Format("Unexpected error"));
}
return file.FileName;
}
return "";
}
I try to download a file and to be able to choose its locationenter image description here
Here is the code I made
in "use of the directory", that's where I define a directory, but I want to be able to choose it via "FolderbrowserDialog"
Please refer to the example here: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.folderbrowserdialog?view=netframework-4.7.2
Specifically:
if(result == DialogResult.OK)
{
openFileName = openFileDialog1.FileName;
try
{
// Output the requested file in richTextBox1.
Stream s = openFileDialog1.OpenFile();
richTextBox1.LoadFile(s, RichTextBoxStreamType.RichText);
s.Close();
fileOpened = true;
}
catch(Exception exp)
{
MessageBox.Show("An error occurred while attempting to load the file. The error is:"
+ System.Environment.NewLine + exp.ToString() + System.Environment.NewLine);
fileOpened = false;
}
I have the following code (or the equivalent thereof):
var provider = new System.Net.Http.MultipartFormDataStreamProvider([...]);
try
{
if (provider.FileData.Count != 0)
{
foreach (System.Net.Http.MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
AddAttachment(file.LocalFileName, file.Headers.ContentDisposition.FileName.Replace("\"", ""));
if (attachmentPaths.Length != 0)
{
attachmentPaths += ";";
}
attachmentPaths += file.Headers.ContentDisposition.Name.Replace("\"", "");
}
}
}
catch (Exception ex)
{ ... }
...
public void AddAttachment(string attachmentFileName, string attachmentName)
{
var AttachmentList = new List<System.Net.Mail.Attachment>();
System.Net.Mail.Attachment newAttachment = new System.Net.Mail.Attachment(attachmentFileName);
newAttachment.Name = attachmentName;
AttachmentList.Add(newAttachment);
}
And I'm getting the "Process cannot access the file ... because it is being used by another process" error. I'd just like to know where my application could be getting the error. I can't tell where in here it is actually trying to access the file. My best guess is in the Attachment constructor, but I'm really not sure.
I was able to figure out a way to test it in a debugger. And the answer was yes, the System.Net.Mail.Attachment constructor is what was trying to access the file.
I'm working on an app that uses Bing's API to search and download images.
Bing's API provides a set of image links and I iterate over them and download each one.
The problem that I'm having is that sometimes the downloaded file size is 0Kb.
I assume that happens because WebClient first creates the filename and then tries to write to it. So when it can't write to it for some reason this happens. The problem is that it happens without throwing an exception so my 'Catch' statement can't catch this and delete the file.
public void imageFetcher(string performerName, int maxNumberOfImages, RichTextBox richTextBox)
{
string performersDirPath = Environment.CurrentDirectory + #"\Performers\";
string performerPath = performersDirPath + performerName + #"\";
if (!Directory.Exists(performersDirPath))
{
Directory.CreateDirectory(performersDirPath);
}
if (!Directory.Exists(performerPath))
{
Directory.CreateDirectory(performerPath);
}
// Searching for Images using bing api
IEnumerable<Bing.ImageResult> bingSearch = bingImageSearch(performerName);
int i = 0;
foreach (var result in bingSearch)
{
downloadImage(result.MediaUrl, performerPath + performerName + i + ".jpg",richTextBox);
i++;
if (i == maxNumberOfImages)
{
break;
}
}
}
The download method:
public void downloadImage(string imgUrl, string saveDestination, RichTextBox richTextBox)
{
if (File.Exists(saveDestination))
{
richTextBox.ForeColor = System.Drawing.Color.Red;
richTextBox.AppendText("The File: " + saveDestination + "Already exists");
}
else
{
try
{
using (WebClient client = new WebClient())
{
client.DownloadFileCompleted += new AsyncCompletedEventHandler(((sender, e) => downloadFinished(sender, e, saveDestination , richTextBox)));
Uri imgURI = new Uri(imgUrl, UriKind.Absolute);
client.DownloadFileAsync(imgURI, saveDestination);
}
}
catch (Exception e)
{
richTextBox.AppendText("There was an exception downloading the file" + imgUrl);
richTextBox.AppendText("Deleteing" + saveDestination);
File.Delete(saveDestination);
richTextBox.AppendText("File deleted!");
}
}
}
This happens also when I try to wait for the client to finish using:
client.DownloadFileAsync(imgURI, saveDestination);
while (client.IsBusy)
{
}
Can anyone please tell me what I'm doing wrong?
In other simular question the solution was to keep the Webclient instance open until download is finished.. I'm doing this with this loop:
while (client.IsBusy){}
Yet the results are the same.
Update:
I resorted to not use webclient, instead I used this code:
try
{
byte[] lnBuffer;
byte[] lnFile;
using (BinaryReader lxBR = new BinaryReader(stream))
{
using (MemoryStream lxMS = new MemoryStream())
{
lnBuffer = lxBR.ReadBytes(1024);
while (lnBuffer.Length > 0)
{
lxMS.Write(lnBuffer, 0, lnBuffer.Length);
lnBuffer = lxBR.ReadBytes(1024);
}
lnFile = new byte[(int)lxMS.Length];
lxMS.Position = 0;
lxMS.Read(lnFile, 0, lnFile.Length);
}
using (System.IO.FileStream lxFS = new FileStream(saveDestination, FileMode.Create))
{
lxFS.Write(lnFile, 0, lnFile.Length);
}
This solves the problem almost complelty, there are still one or two 0KB files but I assume it's because of network errors.
To see possible exceptions - try changing DownloadFileAsync to just DownloadFile - my problem was "Can not create SSL/TLS secure channel". Hope this will help someone.
The process cannot access the file because it is being used by another process
private void DeleteReport()
{
int invid = Convert.ToInt32(Session["InvId"]);
string FileName = invid + "_Report" + ".pdf";
string path1 = Server.MapPath("~/Report/" + FileName);
if (File.Exists(path1))
{
File.Delete(path1);
}
}
The error tells you, that the file is used and can't be deleted. So nothing wrong. As you did not formulate a
real question, lets try to help you in following way.
I guess that only your program is using the report, so good possible, you block the report
somewhere else.
E.g., the following code
string path = "C:\\Temp\\test.txt";
FileStream file = File.Open(path, FileMode.OpenOrCreate);
if (File.Exists(path))
File.Delete(path);
raises the same error. It does not necessarily mean that the process is another process.
What you can do is for example, for testing purpose, install SysInternal
http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx and add following code around your
File.Delete statement. Then you will see, what process uses the file:
try
{
File.Delete(path);
}
catch (Exception)
{
using (Process tool = new Process())
{
tool.StartInfo.FileName = #"C:\Program Files (x86)\SysinternalsSuite\handle.exe"; //Your path
tool.StartInfo.Arguments = path + " /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = #"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern))
{
Process p = Process.GetProcessById(int.Parse(match.Value));
MessageBox.Show(p.ProcessName); // OR LOG IT
}
}
throw;
}
Credit for handle.exe call to https://stackoverflow.com/a/1263609/2707156