C# Handle file errors - c#

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.

Related

How to get rid of clipboard error - intermittent?

Sometimes I get a clipboard error. I've researched this and found that there is a better way to do this, but being new I can't figure out how to integrate it in my code. Trying to make it more stable.
Tried multiple ways to convert the information. Looking to fix this not rewrite everything. I have been down many paths with no luck.
void exportagfile()
{
if (editgrid.Items.Count == 0)
{
MessageBox.Show("Nothing to export.");
}
else
{
try
{
editgrid.SelectAllCells();
editgrid.ClipboardCopyMode =
DataGridClipboardCopyMode.ExcludeHeader;
ApplicationCommands.Copy.Execute(null, editgrid);
String resultat2 =
(string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
String result2 =
(string)Clipboard.GetData(DataFormats.Text);
editgrid.UnselectAllCells();
System.IO.StreamWriter file2 = new
System.IO.StreamWriter
(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) +
#"\MI_imp.txt");
file2.WriteLine(result2.Replace('\t', ',').Replace('»',
','));
file2.Close();
MessageBox.Show(" Exporting File MI_imp.txt to Desktop");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
Trying to stop error when clipboard tries to open. Error: System.Runtime.InteropServices.COMExeption (0x800401D0) OpenClipboard Failed

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();
}
}

C# Try Catch and return back to prompt

I have a try catch block that when it catches an exception I want it to return back to the ReadLine() so the user can try again to enter a valid selection
Console.Write("CSV File: ");
string csvFile = Console.ReadLine();
try
{
List<DictionaryLabels> values = csvRead(csvFile);
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("CSV File not found \nPress any key to contiune");
Console.ReadLine();
}
Your solution to the problem might work, but it does not follow the concept of programming. Try-catch blocks should be used whenever the situation is unexpected instead of the "might happen" scenario.
One way to handle this is described in the code below: You will get first input from the user & validate, if the file exists. Once this is confirmed, You can try to open it. If it fails (e.g. the file does not contain text in CSV format), You should throw an exception.
If it condition in while( condition ) won't be false ( ! File.Exists() ), the loop will run again and again.
using System.IO;
Console.Write("Please enter the path for file:");
string lPath = Console.ReadLine();
while(!File.Exists(lPath))
{
Console.Write("File has not been found. Please enter new path:");
lPath = Console.ReadLine();
}
try
{
List<DictionaryLabels> values = csvRead(lPath);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
bool valid = false
while(!valid)
{
//Rest of the code
}
And you set valid to true at the end of the try and remove the readline from the catch (thanks to Quantic for pointing out my omission).
Console.Write("CSV full path File: ");
string csvFile = Console.ReadLine();
while (!ValidateCsv(csvFile))
{
Console.Write("Retype full path CSV File: ");
csvFile = Console.ReadLine();
}
private static bool ValidateCsv(string csvFile)
{
bool isPathTrue = false;
FileInfo csvFileInfo = new FileInfo(csvFile);
isPathTrue = csvFileInfo.Exists;
return isPathTrue;
}

c# failed to check existed file in directory

there are nothing is inside my test002 folder, by right my output should be is "nothing is inside the folder",but after compile there are nothing prompt.
what i want to do is if there are any .doc file is inside my folder, just upload it
if there are nothing is inside the folder, ask user to upload .doc to required folder.
protected void Button3_Click(object sender, EventArgs e)
{
try
{
string[] chkUserResume = Directory.GetFiles(HttpContext.Current.Server.MapPath(#"~/Enduser/test002/"), "*.doc");
if (chkUserResume!=null)
{
foreach (string name in chkUserResume)
{
Response.Write(name + " is exist");
}
}
else
{
Response.Write("nothing is inside the folder");
}
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
}
The null keyword means that the variable is not set to any real value, which is different from an empty array.
In this case, chkUserResume will never be null, it will be an empty array. You should check that chkUserResume.Length is 0 instead.
You're not checking that chkUserResume is empty:
if (chkUserResume.Length == 0)
{
Response.Write("nothing is inside the folder");
}
else
{
foreach (string name in chkUserResume)
{
Response.Write(name + " is exist");
}
}
However as chkUserResume will never be null there's no need to check for that.

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