Catch Commandline error - c#

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.

Related

C# Handle file errors

I am trying to open a file, and I would like to return e.g. X if the filepath does not exist, Y if the file can't be opened, and Z if it was successful.
However, I can't understand how I can check for the "file can't be opened" error and I am not sure my try-catch is correct so far. I would also like to add another statement to check if the file is already open.
public int Opener(string fileName)
{
string text = "";
try
{
text = File.ReadAllText(fileName);
return "Something to Return";
}
catch (FileNotFoundException)
{
return "Something to Return";
}
You can use this to check the cases you described:
try
{
string text = File.ReadAllText(fileName);
//Z: reading was successful
}
catch (Exception ex)
{
if (ex.InnerException is IOException)
{
//Y: file is already being read
}
else if (ex.InnerException is FileNotFoundException)
{
//X: file does not exist
}
}
The function is declared to return an int, so you need a number there, like -1, 0, or 1. If you want to return a text error message, change the function return type to string.

Exclude System Hardlinks from File.Copy

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.

Check if can create folder/file in specific path

I need to check if the current user has write permissions inside the path. Here an example:
string save_path = #"C:\Windows\somefolder";
string my_dir = Path.DirectorySeparatorChar + "foobar";
//check if specific path are valid
if (!Directory.Exists(save_path)) { return; }
if (Directory.Exists(save_path + my_dir)) { return; }
if (canWriteOnPath(save_path)) {
Directory.CreateDirectory(save_path + my_dir);
} else {
//You are not allowed to save here OR not are launching this application as "administrator"
Directory.CreateDirectory(#"C:\Users\contoso\Documents\foobar");
}
solved in this question:
CurrentUserSecurity cus = new CurrentUserSecurity();
bool flag = cus.HasAccess(new DirectoryInfo(#"C:\Windows"), FileSystemRights.Write);
if (flag) {
//yes create that folder
Directory.CreateDirectory(Path.Combine(save_path, my_dir));
} else {
//NO YOU CANT
Directory.CreateDirectory(#"C:\Users\contoso\Documents\foobar");
}
The robust method would be to Try to create the directory and Catch any resulting exception.
The documentation for Directory.CreateDirectory lists the possible exceptions: IOException, UnauthorizedAccessException, ArgumentException, ArgumentNullException, PathTooLongException, DirectoryNotFoundException.
Although unlikely, it is possible that the permissions changed between your code checking that access is allowed and actually trying to create the directory.

unauthorized access exception c#

I have this method
public void Copy(string sourcePath, string destPath)
{
string[] files= Directory.GetFiles(sourcePath);
for (int i = 0; i < files.Length; i++)
{
try
{
File.Copy(files[i], destPath);
}
catch
{
try
{
File.Replace(files[i], destPath, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
when I run it I get unauthorized access exception , Access denied !
any help in this !
This exception is covered in the documentation for File.Copy:
The caller does not have the required permission.
-or-
destFileName is read-only.
Check the attributes of the file after the first copy. Are the permissions what you expect? Do you need your program to run elevated (as administrator)?
below reasons can possible :
The sourceFileName or destinationFileName parameter specifies a file that is read-only.
-or-
This operation is not supported on the current platform.
-or-
Source or destination parameters specify a directory instead of a file.
-or-
The caller does not have the required permission.
Read link :http://msdn.microsoft.com/en-us/library/9etk7xw2(v=vs.110).aspx
When the problem occurs on a Windows machine, make sure you have disabled "controlled folder access" in the App Windows-Safety or allow folder access to your program. (must have administrator privileges)

JPEG Viewer can't be called from Process.start

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,

Categories