I have an text file which has some settings parameters for my project. My desktop layer reads this file. Therewithal , web layer's project read from from Server's MapPath.
FileStream has no operator to bypass an exception.I have tried to Exists control. But , i just need to bypass FileNotFoundException.
Place the code in a try catch.
try
{
//read
}
catch(FileNotFoundException ex)
{
//do logging for this silent catch
Console.WriteLine(ex);
}
How about this,
if (File.Exists(path)
{
// read file,
}
Another way,
if (File.Exists(path)
{
try
{
// read file,
}
catch (Some other exception related to file, read access violation, etc.)
{
handle exception,
}
}
How about checking the file exists or not?
if so, you can prevent throwing FileNotFoundException.
[Can not provide complete solution/feedback as we aren't sure about your actual implementation]
If(!File.Exists(<path_to_file>)
return;
// continue doing the rest only if file exists
Hope this helps. let us know if require more clarifications. It Would be nice if you could post your method implementation or at least a pseudo code for us to understand the actual problem you trying to solve.
Cheers,
Related
I think this is a rather straightforward issue, but I don't have much information to go on. I have this code to try and read a DWG file into memory, so that I can read and manipulate the data. I am getting an error that the parameter "Value" cannot be null.
While that does let me know something is wrong, how do I proceed in figuring out what exactly this value is so that I can fix it?
string basePath = Path.Combine($"{Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)}", "temp");
string fileName = Path.Combine(basePath, "ATemplateV0.2.dwg");
if(File.Exists(fileName))
{
DwgReader dwgReader = new(fileName);
try
{
DxfModel dxfModel = dwgReader.Read();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
WW CadLib needs a license to run, if you don't have one that may be causing the error.
The code example in the answer from #b166er is referring to an Open Source library called ACadSharp to read dwg/dxf files from one of my repositories.
Right now you can use a pre-release version of it in Nuget
You can pass a onNotification event into the DwgReader constructor that might give you more information. Examples here: https://github.com/DomCR/ACadSharp/blob/master/ACadSharp.Examples/Program.cs
I did find a few similar questions, but they weren't able to point me in the right direction... This may be something entirely stupid, but if anyone could tell me why I can't get a string populated I'd appreciate it. Here's my method that's failing:
private static string passwordTrace { get; set; }
// ... lots of other code
private static void RefreshPassword()
{
try
{
string filePath = "\\\\[server ip]\\share\\folder\\file.abcd";
string npDecrypted;
DateTime lastRefreshDate = Properties.Settings.Default.lastRefresh;
if (DateTime.Now >= lastRefreshDate.AddDays(30))
{
using (StreamReader sr = new StreamReader(filePath))
{
string npEncrypted = sr.ReadLine();
if (npEncrypted.Length != 24)
{
string fr = File.ReadAllText(filePath);
npEncrypted = fr.Substring(0, 24);
}
npDecrypted = Decryptor(npEncrypted);
passwordTrace = npDecrypted; // added for debugging only! remove when done.
secureString npSecure = new SecureString();
foreach (char c in npDecrypted)
{
npSecure.AppendChar(c)
}
Properties.Settings.Default.adminpw = npSecure;
Properties.Settings.Default.Save();
}
}
}
catch (FileNotFoundException fnfe)
{
// code for handling this type of exception
}
catch (NullReferenceException nre)
{
// code for handling this type of exception
}
catch (Exception e)
{
// code to catch ANY other type of exception
}
}
Now, there are no errors or warnings when the VS debugger compiles everything, and it works correctly when debugging. But, if I copy the compiled exe (from C:\project\bin\Debug directory) and run it the issue arises.
The point that says passwordTrace = ... is called at another point by a message box. This works correctly when running via debugger and there aren't any exceptions thrown anywhere (I do have try/catches all over the place), but for whatever reason the PasswordTrace and the Properties.Settings.Default.adminpw don't seem to be holding their value throughout the applications execution.
Also, the file that is being read is an encrypted text file which will always have only 1 line of characters and that line is always 24 characters long. An example would be:
09sdjf09ausd08uf9!%38==
As a final statement, I also copied the app.exe.config and app.pdb to the server directory where I copied the compiled .exe file to see if that had anything to do with it and it didn't fix anything. I also tried running the .exe directly from the Debug directory (the same file that I'm copying elsewhere) and it works correctly. As soon as I move it off of the Local Disk it doesn't work.
So, my suspicions are that it has something to do with the environments working directory, or something to do with how the app is executing. I read something somewhere that noted the default users is not set, but I think that was specifically regarding ASP.NET. If that was the case and the user double-clicking on the .exe didn't have a proper network authentication then what would I do? And if it has something to do with the working directory, how can I circumvent this?
I'm gonna keep fiddling and if I figure it out I'll update this, but I'm so lost at the moment! lol! And for the last time - everything it/was working correctly until copying it to the server location.
Thanks in advance! :)
I use Directory.Exist to test a directory, but I can not distinguish types of errors.
I would like to distinguish if the directory doesn't exist or access is not allowed. I saw this link C# Test if user has write access to a folder but it's quite long and complicated. There is not an easier way?
You can use the Exist method to check whether the directory exists or not. Like this
if(Directory.Exists(directory)) {
// directory exists
try
{
// and is accessible by user...
File.GetAccessControl(filePath);
return true;
}
catch (UnauthorizedAccessException)
{
// but is unable to be accessed...
return false;
}
} else {
// directory doesn't exist, so no file accessible.
}
This is a bit easy and understand code for you. Each of the method is having its own commentary for you.
C# .net Framework 4.0
Is there a simple way to check if you have the rights to run a file?
Before i do this:
//e.g. Press a button
....
string exePath = "D:\something\something.exe";
Process.Start(exePath);
i would like to check if the user has the rights to run that file?
When i'm making the function call Process.Start, windows popsup with a messagebox and says that i'm not authorized to run this application and this application is "D:\something\something.dat" and NOT .exe?
How to check if you have permission to run a exe file?
EAFP: It is Easier to Ask Forgiveness than it is to get Permission.
So, you can surround your code with try/catch block:
try {
Process.Start(path);
} catch (Win32Exception ex) {
// ...
}
and you can use Win32Exception.NativeErrorCode to access the numeric representation of the error code associated with this exception.
For more information about the error codes, check out Win32 System Error Codes.
Try surrounding Proccess.Start with try catch:
//e.g. Press a button
....
string exePath = "D:\something\something.exe";
try
{
Process.Start(exePath);
} catch (Exception e) {
// No permissions or file not found?
}
that'll do the job.
In C#, System.IO.File.Delete(filePath) will either delete the specified file, or raise an exception. If the current user doesn't have permission to delete the file, it'll raise an UnauthorizedAccessException.
Is there some way that I can tell ahead of time whether the delete is likely to throw an UnauthorizedAccessException or not (i.e. query the ACL to see whether the current thread's identity has permission to delete the specified file?)
I'm basically looking to do:
if (FileIsDeletableByCurrentUser(filePath)) {
/* remove supporting database records, etc. here */
File.Delete(filePath);
}
but I have no idea how to implement FileIsDeletableByCurrentUser().
The problem with implementing FileIsDeletableByCurrentUser is that it's not possible to do so. The reason is the file system is a constantly changing item.
In between any check you make to the file system and the next operation any number of events can and will happen. Including ...
Permissions on the file could change
The file could be deleted
The file could be locked by another user / process
The USB key the file is on could be removed
The best function you could write would most aptly be named FileWasDeletableByCurrentUser.
Have you tried System.IO.File.GetAccessControl(filename) it should return a FileSecurity with information about the permissions for that file.
Strictly speaking, an UnauthorizedAccessException means that the path is a directory, so you can use a System.IO.Path.GetFileName(path) type command and catch the argument exception.
But if you want a more holistic solution, use System.IO.File.GetAccessControl as mentioned by Dale Halliwell
As stated above.
Lookup the file permissions and compare with the user who is running the application.
You could always use this aproach as well
bool deletemyfile()
{
try
{
...delete my file
return true;
}
catch
{
return false;
}
}
if it returns false you know it failed if it returns true then.. it worked and file is gone. Not sure what you're after exactly but this was the best I could think of
Of course you can check ReadOnly flags using System.IO and probably ACL security on the file combined with the current user too, but like Mehrdad writes in his comment it would never be full-proof in all cases. So you would need exception handling for the exceptional case at all times (even if its just a top-level catch-all, that logs/shows an "unexpected problem" and kills your application).
You should get the access control list (ACL) of that file.
But this doesn't necessarily mean you could actually delete it because the readonly flag could still be set or another program has locked the file.
Seems like it would be easier to do things in the order of:
Get whatever information you need about the file in order to do the other parts (delete database data, etc)
Try to delete the file
If you successfully delete the file, then carry out the rest of the "cleanup" work. If you don't successfully delete it, return/handle the exception, etc.