FileInfo compact framework 3.5 - cannot find file - c#

I am using the FileInfo class. However, the file info cannot find the file.
The file is called log4Net.config and I have added it to my project. I have set the properties to build action = 'Content' and copy output = 'copy always'
When I run the following code:
FileInfo logfileInfo = new FileInfo("Log4Net.config");
if (!logfileInfo.Exists)
{
Console.WriteLine("Cannot find file: " + logfileInfo.FullName);
return;
}
else
{
XmlConfigurator.Configure(logfileInfo);
}
Exists is always false. The exception is: Could not find file 'Log4Net.config'.
I have checked on my PDA and the Log4Net.config has been copied the PDA and is in the same directory as the executable. So not sure why it cannot find it.
Just some extra info the configure method expects a FileInfo as a parameter.
Am I doing something wrong.
Many thanks for any advice,
Steve

You have to point to the root of your project. FileInfo points to the root of the OS not the root of the exe. So you should change the code like this :
FileInfo logfileInfo = new FileInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + #"\Log4Net.config");

A file not found exception is also thrown when the program does not have the security permission to access the file, so perhaps that's the case?
btw, there's a contradiction in your Post: First you say the file is called "logPDA.config", then it's suddenly called "Log4Net.config". Just to make sure, is the file always named the same?

You are assuming that the Program Folder is the current directory. Afaik that is not the case. You can investigate starting with System.IO.Directory.GetCurrentDirectory()

string logIOFilePath =
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase),
"Log4Net.config");

Related

How to Get current date and create directory Everyday in C#?

get current date and make directory and second when directory is created, in that directory I have to store excel file and also save file as current date.
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
{
Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
}
This code have made directory with current date.
But when I want to store file in that directory, it generates the error:
Could not find a part of the path
'D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
Belove path is store excel file that i have to store.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Actually you are making the directory in a path then you are saving the .xls in another path.
You are making the directory using this path:
"C:\\Users\\Krupal\\Desktop\\" + Todaysdate
Then, here the path where you are trying to save the .xls:
Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"
The error shows the problem clearly, it could not fin this path:
D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
While creating the .xls you are omitting the root path, so the process looks for the path 22-01-2020\22-01-2020.XLS in his working directory D:\WORK\RNSB\RNSB\bin\Debug.
You just need to align those paths: I sugget you to use relative paths, so here how you should fix your code:
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists(Todaysdate))
{
Directory.CreateDirectory(Todaysdate);
}
//then
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
I presume you are running your WinForms application in Debug mode. This means that your current path is [your application path]\bin\Debug. If you look in file explorer, you will find that an executable has been created there. When using StreamWriter without an absolute file name, the file it tries to create is relative to the current execution path (in your case 'D:\WORK\RNSB\RNSB\bin\Debug'). StreamWriter will create a new file, if one does not exist, but it will not create a new folder, and you are passing it Todaysdate + "\\" which is effectively a new folder. Hence you are getting the error message.
To fix your problem, you need to provide the absolute path to your newly created directory thus:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Winforms always expect directories inside Debug Folder, since it's EXE file is inside Debug and try to find it inside Debug folder.
In error it clearly shows that it is looking inside "Debug" folder.
Can you check whether File Exists in the mentioned folder created by you in C Drive.
// To Write File
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
You can follow this MSDN Post, hope it helps, if Yes, please Upvote it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

Rename existing file name

I have the following code which copies a file to a specific folder and then renames it.
When a file with that name already exists I get the following exception:
Cannot create a file when that file already exists
Is there a way to overwrite the file and rename it? or I should delete the old one and then change the name?
Here is my code:
File.Copy(FileLocation, NewFileLocation, true);
//Rename:
File.Move(Path.Combine(NewFileLocation, fileName), Path.Combine(NewFileLocation, "File.txt"));
Try to use only:
if (File.Exists("newfilename"))
{
System.IO.File.Delete("newfilename");
}
System.IO.File.Move("oldfilename", "newfilename");
One simple option is to delete the file if it exists:
if (System.IO.File.Exists(newFile)) System.IO.File.Delete(newFile);
System.IO.File.Move(oldFile, newFile);
Something like that should work.
You're correct, File.Move will throw an IOException if/when the filename already exists. So, to overcome that you can perform a quick check before the move. e.g.
if (File.Exists(destinationFilename))
{
File.Delete(destinationFilename);
}
File.Move(sourceFilename, destinationFilename);
You should use File.Exists rather than letting the Exception throw. You can then handle if the file should be overwrote or renamed.
Step 1 : as a first step identify wether the file exists or not before copying the file.
using File.Exists() method
Step 2: if the file already exists with same name then delete the existing file using File.Delete() method
Step 3: now copy the File into the new Location using File.Copy() method.
Step 4: Rename the newly copied file.
Try This:
string NewFilePath = Path.Combine(NewFileLocation, fileName);
if(File.Exists(NewFilePath))
{
File.Delete(NewFilePath);
}
//Now copy the file first
File.Copy(FileLocation, NewFileLocation, true);
//Now Rename the File
File.Move(NewFilePath, Path.Combine(NewFileLocation, "File.txt"));
I always use MoveFileEx with the flag MOVEFILE_REPLACE_EXISTING.
Limitations:
It needs to use PInvoke, so it means your code will only work on the Windows platform.
This flag MOVEFILE_REPLACE_EXISTING only work with File(Doesn't work with Folder)
If lpNewFileName or lpExistingFileName name a directory and lpExistingFileName exists, an error is reported.

System.UnauthorizedAccessException while creating a file

I was trying to write a code so that I could log the error messages. I am trying to name the file with the date and would like to create a new log file for each day. After going through a little look around, I came with the following code...
class ErrorLog
{
public void WriteErrorToFile(string error)
{
//http://msdn.microsoft.com/en-us/library/aa326721.aspx refer for more info
string fileName = DateTime.Now.ToString("dd-MM-yy", DateTimeFormatInfo.InvariantInfo);
//# symbol helps to ignore that escape sequence thing
string filePath = #"c:\users\MyName\mydocuments\visual studio 2012\projects\training\" +
#"discussionboard\ErrorLog\" + fileName + ".txt";
if (File.Exists(filePath))
{
// File.SetAttributes(filePath, FileAttributes.Normal);
File.WriteAllText(filePath, error);
}
else
{
Directory.CreateDirectory(filePath);
// File.SetAttributes(filePath, FileAttributes.Normal)
//Throws unauthorized access exception
RemoveReadOnlyAccess(filePath);
File.WriteAllText(filePath, error);
}
}
public static void RemoveReadOnlyAccess(string pathToFile)
{
FileInfo myFileInfo = new FileInfo(pathToFile);
myFileInfo.IsReadOnly = false;
myFileInfo.Refresh();
}
/*Exception thrown:
* UnAuthorizedAccessException was unhandled.
* Access to the path 'c:\users\anish\mydocuments\visual studio 2012\
* projects\training\discussionboard\ErrorLog\04\12\2013.txt' is denied.
*/
}
I found a forum that has discussed about a similar problem but using
File.SetAttrributes(filePath, FileAttributes.Normal) did not help neither did the RemoveReadOnlyAccess (included in the code above). When I check the properties of the folder, it has read only marked but even when I tick that off it comes back again. I checked the permissions on the folder and except for the special permission, which I was not able to change, everything is allowed.
Any suggestion on how I should proceed would be appreciated.
Why is access to the path denied? the link discusses about a similar problem, but I wasn't able to get my thing working with suggestions listed there.
Thanks for taking time to look at this.
Your path is strange : "My documents" directory must be "C:\Users\MyName\Documents\"
You can use Environment in order to correct it easily :
String myDocumentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Note that it will acces to "My documents" folder of the user that running your exe.
Second error, CreateDirectory must have a path in argument, not a file. using like you do will create a sub-directory with the file name. So you can't create a file with this name !
Try this :
String fileName = DateTime.Now.ToString("d", DateTimeFormatInfo.InvariantInfo);
String filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
+ #"\visual studio 2012\projects\training\discussionboard\ErrorLog\";
String fileFullName = filePath + fileName + ".txt";
if (File.Exists(fileFullName ))
{
File.WriteAllText(fileFullName , error);
}
else
{
Directory.CreateDirectory(filePath);
[...]
}
}
Some possible reasons:
your app is not running under account which is allowed to access that path/file
the file is being locked for writing (or maybe reading too) by some other process
The first situation could be solved by checking under which account the process is running and verifying that the account has the appropriate rights.
The other situation can be solved by checking if any other process is locking the file (e.g. use tools like 'WhosLocking' or 'ProcessExplorer'
I had to run my app as an administrator in order to write to protected folders in c:. For example if debugging your app in visual studio make sure to right click on "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" and choose "Run As Administrator". Then open your solution from there. My app was trying to write to the root of c:\
Check your antivirus, it might be blocking the file creation.

Write a text file to a sub-folder

I am trying to write out a text file to: C:\Test folder\output\, but without putting C:\ in.
i.e.
This is what I have at the moment, which currently works, but has the C:\ in the beginning.
StreamWriter sw = new StreamWriter(#"C:\Test folder\output\test.txt");
I really want to write the file to the output folder, but with out having to have C:\ in the front.
I have tried the following, but my program just hangs (doesn't write the file out):
(#"\\Test folder\output\test.txt");
(#".\Test folder\output\test.txt");
("//Test folder//output//test.txt");
("./Test folder//output//test.txt");
Is there anyway I could do this?
Thanks.
Thanks for helping guys.
A colleague of mine chipped in and helped as well, but #Kami helped a lot too.
It is now working when I have:
string path = string.Concat(Environment.CurrentDirectory, #"\Output\test.txt");
As he said: "The CurrentDirectory is where the program is run from.
I understand that you would want to write data to a specified folder. The first method is to specify the folder in code or through configuration.
If you need to write to specific drive or current drive you can do the following
string driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
string path = diveLetter + #"Test folder\output\test.txt";
StreamWriter sw = new StreamWriter(path);
If the directory needs to be relative to the current application directory, then user AppDomain.CurrentDomain.BaseDirectory to get the current directory and use ../ combination to navigate to the required folder.
You can use System.IO.Path.GetDirectoryName to get the directory of your running application and then you can add to this the rest of the path..
I don't get clearly what you want from this question , hope this get it..
A common technique is to make the directory relative to your exe's runtime directory, e.g., a sub-directory, like this:
string exeRuntimeDirectory =
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
string subDirectory =
System.IO.Path.Combine(exeRuntimeDirectory, "Output");
if (!System.IO.Directory.Exists(subDirectory))
{
// Output directory does not exist, so create it.
System.IO.Directory.CreateDirectory(subDirectory);
}
This means wherever the exe is installed to, it will create an "Output" sub-directory, which it can then write files to.
It also has the advantage of keeping the exe and its output files together in one location, and not scattered all over the place.

Get File From an Assembly

I want to read a file path from the following structure
The Structure is like : AssemblyName -> MyFiles (Folder) -> Text.txt
Here I want to get the path of the Text.txt. Please help
I think what you're looking for is a file embedded in the assembly. Check out this question. The first answer explains how to set up an embedded file, as well as how to get it from code.
You can do
string assemblyPath = Assembly.GetExecutingAssembly().Location;
string assemblyDirectory = Path.GetDirectoryName(assemblyPath);
string textPath = Path.Combine(assemblyDirectory, "MyFiles", "Test.txt");
string text = File.ReadAllText(textPath);
...just to split it up some...but you could write it all in one line needless to say...
alternatively, if your Environment.CurrentDirectory is already set to the directory of your executing assembly's location, you could just do
File.ReadAllText(Path.Combine("MyFiles", "Text.txt"));
Jeff has covered how you get the path, wrt your comment on his answer is the file you want to open actually included in your project output?
Under the properties pane for the relevant file look at the Copy to Output Directory option - it generally defaults to Do not copy. You will want to set it to Copy Always or Copy if Newer if you want to include a file in the output directory with your compiled program.
As a general note you should always wrap any IO in an appropriate try catch block or use the static File.Exists(path) method to check whether a file exists

Categories

Resources