Catching File Exceptions using c# - c#

The below is what I am wrestling with today using Visual Studios Console App.
What I want to happen, which currently isn't, is when the Console App opens, and I type the first "checksPath" in, if this turns out to not exist, I want it to say that the path is wrong, and either, let the user try again, or close the app. If the path is valid, then it moves onto the next "reportDest", and the same applies. If it's an invalid path, I want a message saying so, with the option of trying again, or closing the app. If both paths entered (eventually) are valid, I want a message to say that the report will now produce. The rest of the script that produces the report is perfectly fine, it's just the bit i've put below that's troublesome.
string checksPath;
Console.Write("Please enter the source path for the Checks Workbook, including the name of the file (Not including the file extension): ");
checksPath = Console.ReadLine() + ".xlsx";
try
{
if (File.Exists("checksPath"))
throw new FileNotFoundException();
}
catch (FileNotFoundException e)
{
Console.WriteLine("Invalid path - Please close the app and try again!");
Console.ReadLine();
}
string reportDest;
Console.Write("Please enter the folder location and file you wish your report to go to (Not including the file extension): ");
reportDest = Console.ReadLine() + ".xlsx";
try
{
if (File.Exists("reportDest"))
throw new FileNotFoundException();
}
catch (FileNotFoundException e)
{
Console.WriteLine("Invalid path - Please close the app and try again!");
Console.ReadLine();
}
Console.WriteLine("Your report will now produce");

Since you need to continually ask a question until the user gets it right, you will need a loop. Next in that loop you need to check if the path exists.
bool run = true;
while (run)
{
Console.Clear();
Console.WriteLine("Enter Path:");
string answer = Console.ReadLine();
if (Directory.Exists(answer)) run = false;
else
{
Console.WriteLine("Path Does not exists. Try again. Press enter to continue...");
Console.ReadLine();
}
}

Related

How to open files on my desktop using C# Net.Core script?

Is there any way to make a link in C# Net Core? And whenever the user types in the user input command window to open a certain file on my PC?
Like for example:
Console.Write("Open project?: ");
string answer = Console.ReadLine();
If (answer == "yes")
{
//Open file cmd here, and one linked file for example.
}
In order to open a file or program programmatically, you firs have to know the location of that file then be sure that such file is on disk otherwise if you try to open it, it throws an error.
using System;
using System.Diagnostics;
Console.Write("Open project?: ");
string answer = Console.ReadLine();
If (answer == "yes")
{
try
{
Console.WriteLine("\nOpening file from your documents folder....");
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\myfile.txt";
Process.Start(path);
//Or a program
Process.Start("notepad.exe");
}
catch (Win32Exception ex)
{
Console.WriteLine(ex.Message);
}
}

How to fix "used by another process" error when editing a text file which was opened using Process.Start()?

I' making a console application in c#. I used a Process.Start() function to open a text file, which can be edited directly in notepad and program waits for the notepad to close. But when trying to save the file, a warning message pops up saying "File being used by another process".
Since I'm a beginner, I don't know how to fix this problem. I know about FileAccess, FileMode, FileStream but I have never used them and don't think they will help at this point.
This is the constructor before Main() method
public AccountApplication()
{
Process process = Process.Start("notepad.exe", textFilePath);
process.WaitForExit();
}
And part of the Main() method where this constructor is used
TextFileWriting:
AccountApplication openFile;
Console.Clear();
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("Enter a file name: ");
string filename = Console.ReadLine();
if (filename == "")
{
goto TextFileWriting;
}
textFilePath = Path.Combine(currentUserFolder, filename + ".txt");
if (File.Exists(textFilePath))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("File You specified already has been created. Do you want to overwrite or edit it? (edit/overwrite)");
string userAnswer = Console.ReadLine();
if (userAnswer == "edit")
{
openFile = new AccountApplication();
goto MainMenu;
}
else if (userAnswer == "overwrite")
{
File.CreateText(textFilePath);
openFile = new AccountApplication();
goto MainMenu;
}
else if (userAnswer == "")
{
goto TextFileWriting;
}
}
else if (!File.Exists(textFilePath))
{
File.CreateText(textFilePath);
openFile = new AccountApplication();
goto MainMenu;
}
Notepad opened and the program was waiting for it to close. One thing user was unable to do is to save the changes made.
The line below creates a StreamWriter for you:
File.CreateText(textFilePath);
It is intended to be used like this:
using (var writer = File.CreateText(textFilePath))
{
writer.WriteLine("Hi!");
};
If you don't want to write anything to the file, just close the StreamWriter immediately:
File.CreateText(textFilePath).Close();

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

Bulk replace or remove a character in file names

I have a little utility I'm writing that will let the user replace 1 character for another in a filename from a specific directory the user chooses.
The idea is to let the user replace an "_" or any other character they want with any other character they want or just remove it altogether.
EDIT: After taking the information I learned from your responses and a little Google searching to understand how those commands worked, I came up with this code. Any feedback would be nice.
private static void myremovechar()
{
//subprocedure to modify file names by removing or replacing characters NO SUB DIRECTORIES
//Ask user where the files are located and store value in string mybadfilesource
Console.Clear();
Console.WriteLine("Where are your files located");
Console.WriteLine(#"Example: D:\folder\subfolder\");
string mybadfilesource = Console.ReadLine();
//Ask user what character to remove and store value in string mychartodelete
Console.WriteLine("What character do you want to remove");
Console.WriteLine("Only 1 Character allowed");
string mychartodelete = Console.ReadLine();
//Ask user what character to replace mychartodelete with and store value in string mychartoreplace
//if user just hits enter, mychartodelete will just be deleted
Console.WriteLine("What character do you want to replace it with");
Console.WriteLine("Press enter to just delete previously selected Character");
Console.WriteLine("Only 1 Character allowed");
string mychartoreplace = Console.ReadLine();
try
{
//store list of files from mybadfilesource in var filelist
var filelist = Directory.EnumerateFiles(mybadfilesource);
foreach (string file in filelist)
{
//renames the files by Replacing mychartodelete with mychartoreplace
var newfile = string.Format("{0}{1}",Path.GetFileNameWithoutExtension(file).Replace(mychartodelete, mychartoreplace),Path.GetExtension(file));
File.Move(file, Path.Combine(mybadfilesource, newfile));
}
}
//Error Checking Process - Prints error message
catch (Exception e)
{
Console.WriteLine(e.Message);
}
//tell user the process is done and return to Main Menu
Console.WriteLine("Finished - Press Enter to Return to Main Menu");
Console.ReadLine();
Console.Clear();
Main();
}
Thank you all for your help
There's a lot of wrong here:
You're calling Replace on the wrong variable
If you use the right variable, you'll still get an error for modifying a variable in a foreach loop
You're not really renaming anything, you're not applying anything back to the actual file.
try this:
foreach (var file in Directory.EnumerateFiles(mybadfilesource))
{
var newfile = string.Format("{0}{1}",
Path.GetFileNameWithoutExtension(file).Replace(mychartodelete, mychartoreplace),
Path.GetExtension(file));
File.Move(file, Path.Combine(mybadfilesource, newfile));
}
Be sure to just get the filename without the path or extension, or else you'd be changing those too

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 ?

Categories