I'm I'm trying to upload a file to my server via FTP, and it's not working. The Upload complete event is triggered, and there are no exceptions being caught by the try catch block. This should be pretty straightforward right? What am I missing here? I know the web directory is right, because I copied and pasted it right from my browser after navigating to it, and the file that I'm uploading is correct because it makes it past the File.Exists, if statement.
string strWebDirectory = "ftp://sharedhosting.com/mydomain.com/wwwroot/Images/" + txt.Text.Trim();
System.Net.WebClient wc = new System.Net.WebClient();
wc.Credentials = new System.Net.NetworkCredential("usr", "psw");
wc.UploadFileCompleted += (s, ev) => UploadProgressCompleted();
if (File.Exists( strStartUpPath + "Upload\\" + txtFile.Text))
{
try
{
wc.UploadFileAsync(new Uri(strWebDirectory), strStartUpPath + "Upload\\" + txtFile.Text);
}
catch (Exception ex)
{
}
}
Any help is appreciated. Thank you.
Look at the Error property. Probably, there was an error.
You need to await/wait on UploadFileAsync to observe the exception it is throwing.
try
{
await wc.UploadFileAsync(new Uri(strWebDirectory), strStartUpPath + "Upload\\" + txtFile.Text);
}
catch (Exception ex)
{
}
Related
I'm trying to download files from my server through android using xamarin and I have no error but I don't find any file where it is supposed to be.
I'm using that code:
System.Net.WebClient Client = new System.Net.WebClient();
Console.WriteLine("Start downloading...");
try
{
var documentsFolder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.MyDocuments);
if(!File.Exists(documentsFolder))
Directory.CreateDirectory(documentsFolder);
var fileNameAndPath = Path.Combine (documentsFolder, "tmpfile");
Client.DownloadFile(new Uri(url), fileNameAndPath);
}
catch(System.Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
while(e.InnerException!=null)
{
e=e.InnerException;
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
Console.WriteLine("...end downloading");
There's no error catched but no file downloaded, I tried several special paths but none seems to work. Can someone help me ?
So my problem is that I want to export my user account.
But inside C:\%user%\AppData\Local\ are System Hardlinks e.g.: Application Data which I obviously have no right to use them.
Is there a way to exclude those System Hardlinks from the copying process?
I'm not sure what you mean with hard links, but this might help you
foreach (var dir in new DirectoryInfo(#"c:\users\xxxxxx\AppData\Local").GetDirectories())
{
if (dir.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
Console.WriteLine(dir.Name + " is symbolic, skip it");
}
else
{
//do your copy here
}
}
So I fixed the issue with Exception handling, doing it this way:
FileInfo[] sourceFiles = null;
try {
sourceFiles = new DirectoryInfo(sourcePath).GetFiles();
} catch (Exception ex) {
WriteLog(LogPath, ex + "");
return;
}
Since I'm a bit new to exception handling, I couldn't work it out for the first few hours on this problem.
C# / .NET 3.5, WindowsForms.
I have this Windows form that displays an image from a file, and whenever user saves the record this code is executed:
string oldLoc = itemsBO.ImageLoc;
if (oldLoc != SystemSettings.NoImageLocation)
{
if (File.Exists(oldLoc))
{
try { File.Delete(oldLoc); }
catch (IOException ex)
{
MessageBox.Show("1 - " + ex.GetType().ToString() + " " + ex.Message);
}
}
}
string saveLoc = itemsBO.ImageSearchLoc + ".jpg";
if (File.Exists(saveLoc))
{
try { File.Delete(saveLoc); }
catch (IOException ex)
{
MessageBox.Show("2 - " + ex.GetType().ToString() + " " + ex.Message);
}
}
try
{
if (pictureBox2.Image != null)
pictureBox2.Image.Save(saveLoc, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (IOException ex)
{
MessageBox.Show("3 - " + ex.GetType().ToString() + " " + ex.Message);
}
Disregard the poor MessageBox messages, but it errors out in each Catch statement. It can't delete the "existing" Image because it says it's in use by another process. Can't save because a file exists in that same path because it's not deleting.
This is the code that sets the Image when they try to add a new picture;
Image clipImage = Clipboard.GetImage();
if (tabControl2.SelectedTab == tabPage5)
{
pictureBox1.Image = clipImage;
itemsBO.IsDirtyImage = true;
}
else if (tabControl2.SelectedTab == tabPage6)
{
pictureBox2.Image = clipImage;
itemsBO.IsDirtyImage2 = true;
}
Then when the form loads up an existing record with an image, this is the code used to fetch/display it:
byte[] bits = File.ReadAllBytes(imgfil);
msImage = new MemoryStream(bits, 0, bits.Length);
if (tabControl2.SelectedTab == tabPage5)
pictureBox1.Image = Image.FromStream(msImage);
else if (tabControl2.SelectedTab == tabPage6)
pictureBox2.Image = Image.FromStream(msImage);
imgfil being a path to the image, of course.
Absolutely no idea where to begin...
I have this Windows form that displays an image from a file, and whenever user saves the record
If you're still displaying the image when they save the file, the application will still be accessing the file if I'm not mistaken. Try disposing of the file first, probably by setting the picture box's (or whatever you're using to display the image) image to null, or load a blank picture before you perform the operation.
If it says file in use by another process, well then it must be in use by another process :)
Have you tried monitoring the file lock using Process Explorer.
Once you have identified what's holding your file, close that file handle using Process Explorer and then try to run your code.
This might help-
How to find out what processes have folder or file locked?
So I had inherited this application from another user, turns out the pictureBoxes were having their Image set in another chunk of code independent of that third block of code in the original post. It was because of this that the IOException was happening :(
Here is my code
if (row.Cells[5].Value.ToString().ToUpper() == "JPG")
{
try
{
// string notepadPath = Path.Combine(Environment.SystemDirectory, "MSPAINT.exe");
string notepadPath = Path.Combine(Environment.SystemDirectory, "JPEGViewer.exe");
if (File.Exists(notepadPath))
Process.Start(notepadPath, location);
else
throw new Exception("Can't locate Notepad");
}
catch (Exception ee)
{
MessageBox.Show("Exception is " + ee.Message);
}
}
Even Though the String notepadPath contains the Folder and executable C:\Windows\system32\JPEGViewer.exe the line ** if (File.Exists(notepadPath)) doesn't find the exe even though it is there. If I attempt to bypass the Exist and perform the Process.Start(notepadPath, location); It throws an exception The system cannot find the file specified
**
Please note that this same code works perfectly when calling MSPAINT.EXE
Any ideas will be greatly appreciated,
I am having trouble wrapping my head around the async/await functionality in .NET 4.5. I am using the code below in a Web API controller to catch multiple files from a form along with some other form data. I have no control over the form or how it sends the data.
What I want to do is receive the files, get data from the form, read a database based on that form data, move the file(s), and update another database table. With the below code I have no trouble getting the files or form data. I get data from the database based on the formID passed in the form data.
It is when I uncomment the code near the bottom for writing back to the database that I run into issues. If I had three files, only one of them gets moved before the catch block catches an exception. I am assuming that my problem is related to the fact that the PostFile method is async.
What is the proper way of writing this code so that it works?
public async Task<HttpResponseMessage> PostFile()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = GetRootPath();
var provider = new MyMultipartFormDataStreamProvider(root);
string logfile = root + "/form_data_output.txt";
try
{
// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
string form_id = provider.FormData.Get("FormId");
string driver_id = GetDriverID(form_id); // returns an int as a string
string location = ConfigurationManager.AppSettings["storagePath"];
location += form_id + "\\";
//// make sure the new directory exists
if (!Directory.Exists(location))
{
Directory.CreateDirectory(location);
}
var keys = provider.FormData.Keys.Cast<string>();
foreach (var k in keys.Where(k => k.StartsWith("FormViewer") == true))
{
string filename = provider.FormData.Get(k) + ".pdf";
string type_key = "FormType_" + k.Substring(k.IndexOf('_') + 1);
string type_value = provider.FormData.Get(type_key);
// setup the full path including filename
string path = root + "\\" + filename;
string newFullPath = location + filename;
// move the file
File.Move(path, newFullPath);
if (File.Exists(newFullPath))
{
if (File.Exists(newFullPath))
{
try
{
string conn_str = ConfigurationManager.ConnectionStrings["eMaintenanceConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(conn_str))
{
SqlCommand cmd = new SqlCommand("INSERT INTO eSubmittal_Document VALUES (null,#driver_id,#location,#doctype)");
cmd.Parameters.AddWithValue("#driver_id", driver_id);
cmd.Parameters.AddWithValue("#location", location);
cmd.Parameters.AddWithValue("#doc_type", type_value);
conn.Open();
int c = await cmd.ExecuteNonQueryAsync();
conn.Close();
}
}
catch (Exception e)
{
LogEntry(logfile, e.Message);
}
}
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
async and await provide natural program flow for asynchronous code. So for the most part, you can just think about code the way you normally think about it:
It is when I uncomment the code near the bottom for writing back to the database that I run into issues. If I had three files, only one of them gets moved before the catch block catches an exception.
Here's what I get from this:
Your database code is throwing an exception.
When the exception is thrown, it leaves the foreach loop to go to the catch handler.
Nothing unexpected there...
It's hard to help very much without knowing the exception, but performing a synchronous database operation inside an async method seems like a bad idea to me. Try changing your code to use:
int c = await cmd.ExecuteNonQueryAsync();