JPEG Viewer can't be called from Process.start - c#

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,

Related

File.Exists + File.Move Erroring "The process cannot access the file because it is being used by another process."

I have what I thought would be a very simple file mover script. It checks for a file and moves it to a new directory if it exists:
if (File.Exists(_collection[x,0]))
{
System.IO.File.Move(_collection[x, 0], _moveTo);
MessageBox.Show("File moved because it was stale.");
}
It passes the check that the file exists, but then errors on the following line when trying to move it stating that the file is being used by another process. I can only assume that File.Exists is causing it to hang up somehow, but can't find a solution from anyone else who had this problem.
try this code:
string filePathNameToMove = "";
string directoryPathToMove = "";
if (File.Exists(filePathNameToMove))
{
string destinationFilePathName =
Path.Combine(directoryPathToMove, Path.GetFileName(filePathNameToMove));
if (!File.Exists(destinationFilePathName))
{
try
{
File.Move(filePathNameToMove, destinationFilePathName);
Console.WriteLine("File Moved!");
}
catch (Exception e)
{
Console.WriteLine("File Not Moved! Error:" + e.Message);
}
}
}
In case anyone else has this problem. In my case, the file had been opened in Excel and Excel was never garbage collected after being terminated. So the OS still thought the file was being accessed. I did the following, crude, but it works.
for (int i = 1; i > 0; i++)
{
try
{
File.Move(sourceFileName, destinationFileName);
break;
} catch
{
GC.Collect();
}
}

UploadFileAsync not working - WPF

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)
{
}

IO Exception - File In Use By Another Process

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 :(

Trouble deleting a file from c:\windows\system32 using C#

Not quite sure why I can't get this file to delete. I'm logged in as Admin, tried "Run as Admin", tried running in the same folder, tried setting permissions on the file, tried creating a test 1.txt file to delete and no luck. It is acting like the file isn't there. I can see it in Windows Explorer. Please any help is welcome. Thank you for your time.
public void deleteFile(string FileToDelete)
{
//sets system32 to system32 path
string system32 = Environment.SystemDirectory + #"\";
//File.SetAttributes(#system32 + FileToDelete, FileAttributes.Normal);
try
{
//check if file exists
if (!File.Exists(#system32 + #FileToDelete))
{
//if it doesn't no need to delete it
Console.WriteLine("File doesn't exist or is has already been deleted.");
//Console.WriteLine(system32 + FileToDelete);
} //end if
//if it does, then delete
else
{
File.Delete(system32 + FileToDelete);
Console.WriteLine(FileToDelete + " has been deleted.");
} //end else
} //end try
//catch any exceptions
catch (Exception ex)
{
Console.WriteLine(Convert.ToString(ex));
} //end catch
} //end DeleteFile
I created a test file "test.txt" and it worked no problem. I should not that I didn't use the method you posted, but rather used the contents of your supplied method and used them within the main() method of a console application.
ou should also add ReadLine() to display any messages that are returned.
This is what I used, not that it's much different from what you supplied. If this code doesn't work for you then it must be a system privileged issue.
static void Main(string[] args)
{
string FileToDelete = "test.txt";
//sets system32 to system32 path
string system32 = Environment.SystemDirectory + #"\";
try
{
//check if file exists
if (!File.Exists(system32 + FileToDelete))
{
//if it doesn't no need to delete it
Console.WriteLine("File doesn't exist or is has already been deleted.");
//Console.WriteLine(system32 + FileToDelete);
Console.ReadLine();
} //end if
//if it does, then delete
else
{
File.Delete(system32 + FileToDelete);
Console.WriteLine(FileToDelete + " has been deleted.");
Console.ReadLine();
} //end else
} //end try
//catch any exceptions
catch (Exception ex)
{
Console.WriteLine(Convert.ToString(ex));
Console.ReadLine();
} //end catch
}
Try this one out
check if file exist on 64 bits system using File.Exists
If you're using Vista / Windows 7, maybe you're running into file virtualization issues. Have you tried adding a manifest with a <requestedExecutionLevel level="requireAdministrator"/> line in it ?

Catch Commandline error

I am trying to catch an error with an incorrect commandline parameter for the application of form
Myapp.exe myFile.txt
The application however throws an "Unhandled exception - The path is not of legal form".
Below is my code and I am wondering why it does not show the message box as provided in the code? Thanks.
String[] cmdlineArgs = Environment.GetCommandLineArgs();
if (cmdlineArgs.Length == 2)
{
try
{
if (File.Exists(cmdlineArgs[1].ToString()))
ConfigParameters.SetConfigParameters(cmdlineArgs[1].ToString());
else
{
MessageBox.Show("Configuration file does not exist.Restarting...");
Environment.Exit(1);
}
}
catch (Exception ex)
{
}
If you pass an invalid path to File.Exists (such, C:\D:/E:\), you get that exception.
Check for improper characters in the file path (e.g. '>' <'>, etc...).
http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx
&
http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx
You should modify your code like bellow is more better :D
String[] cmdlineArgs = Environment.GetCommandLineArgs();
if (cmdlineArgs.Length == 2)
{
try
{
if (File.Exists(cmdlineArgs[1].ToString()))
ConfigParameters.SetConfigParameters(cmdlineArgs[1].ToString());
}
catch (Exception ex)
{
MessageBox.Show("Configuration file does not exist.Restarting...");
Environment.Exit(1);
}
}
Because when your file path contain some special characters(<, >, ?, *, etc), the File.Exists() maybe throw exception as you see.

Categories