How to Create A File Even If Sub-Directories Dont Exist - c#

How can I create a file even if the some sub-directories dont exist? I am aware of this Question and its answer that suggests I use Directory.CreateDirectory(path) to create both my file and its directories.
But when I attempt to create my file using Directory.CreateDirectory(path) it creates the file as a directory/folder and not as a file?
Directory.CreateDirectory (#"C:\Users\me\AppData\LocalLow\company\product\database.db");
Why is database.db a folder and not a file? Am I doing something wrong? How can I create a file even if the some sub-directories dont exist?

You need to specify the directory path to the CreateDirectory method, not the full file path. You can extract this from the full path using GetDirectoryName:
string filePath = #"C:\Users\me\AppData\LocalLow\company\product\database.db";
string dirPath = Path.GetDirectoryName(filePath);
// gives #"C:\Users\me\AppData\LocalLow\company\product"
Directory.CreateDirectory(dirPath);
File.Create(filePath); // can use any file API call here, such as File.Open

Related

File not found on File.Exists with spaces in path

If my executable is running from a path with no spaces, this
if(!File.Exists(#"\program.exe"))
MessageBox.Show("File not found");
doesn't fire. But, if the program executes from a path with spaces, like C:\Program Files\etc\ I get a file not found. My executable application and program.exe lies in the same folder.
How can I avoid this?
Though it may seem like the path has something to do with it, it's the Working Directory. Try this code:
var path = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"program.exe");
if (!File.Exists(path))
The path in which is it launched wouldn't cause that code to fail. However, when the working directory isn't what's expected; that will.
Furthermore, never assume that you're in a specific directory. Always provide a fully qualified path. Objects like the SaveFileDialog and OpenFileDialog can change the working directory on you at runtime.
Just get the execution directory path and append it to your exe file name
string DirPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
if(!File.Exists(DirPath + #"\program.exe"))
MessageBox.Show("File not found");
I would simply remove "\" from the argument of the method File.Exists(#"program.exe"), and check the current working directory by GetCurremtDirectory to be sure that relative path you are passing (that is relative path) constructs correct full path to executable.
File.Exist(#"\program.exe")
will check for program.exe at the root of the drive, eg c:\program.exe if your program is running from c:
To check the existence of your file in the "current directory", you have not to put the "\" character. So:
if(!File.Exists("program.exe"))
MessageBox.Show("File not found");
Here a little explanation.

Silverlight: How to load files in directory included in XAP folder

I have a folder with a list of files that I've included in my silverlight solution as "Content". I know how to load individual files using Application.GetResourceStream(), but I wish to load an entire directory with multiple files in it.
Attempted to use DirectoryInfo but it throws a Securityexception, and using Application.GetResourceStream() with a directory path returns null.
I solved by using a standard file naming convention, with a specified index in the filename, and then I just build each filename with using a loop and the index of the loop and load each stream into an array.

C#.NET - Error Logging and Relative File Paths

I have a class in C# that saves an error message in a log file in case of an exception. Now I want to save the log file in the same folder containing the application's (in my case, a website) files. I tried using Environment.CurrentDirectory however it is not retrieving the path to my website. What can I do please to make use of a relative file path which points inside the website's directory?
Here is the class' code. As you can see, the path is absolute. I want to change it to a relative file path pointing to a folder in my website's directory.
Usually Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) returns the path where the current assembly resides. You could use
string logName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MyLogFile.log");
to create the log file name.
Question is really whether logging to the application's folder is permitted by the OS. Also, for Web-applications, the log file would be publically visible and accessible through the web browser.
For a website use:
HttpContext.Current.Server.MapPath("~/");
You might also could try this solution:
string path = AppDomain.CurrentDomain.BaseDirectory + "anotherFolder";
This would put the base dir of the app and a folder inside of the project!

Add files to ZIP without paths, using SharpZipLib

I need to combine 3 files into 1 zip file and make it available to download for the user. I am able to achieve my requirement except one thing: it zips the files into the subfolders.
For example, my files are located like the following:
C:\TTCG\WebSites\Health\ABC.CSV
C:\TTCG\WebSites\Health\XYZ.CSV
C:\TTCG\WebSites\Health\123.CSV
But in the zip file, it zip the files in the folder by using "TTCG\WebSites\Health\" as the path. Please see the attach file.
I don't want the folders in the path. I just want 3 files in the zip file without folders. How can I achieve that?
My codes to generate the zip file is as below:
ZipFile z = ZipFile.Create(Server.MapPath("~" + #"\Accident.zip"));
//initialize the file so that it can accept updates
z.BeginUpdate();
//add the file to the zip file
z.Add(Server.MapPath("~" + #"\ABC.csv"));
z.Add(Server.MapPath("~" + #"\XYZ.csv"));
z.Add(Server.MapPath("~" + #"\123.csv"));
//commit the update once we are done
z.CommitUpdate();
//close the file
z.Close();
Based on the FAQ, you have to strip the folder path out manually:
How can I create a Zip file without folders?
Remove the path portion of the filename used to create a ZipEntry
before it is added to a ZipOutputStream
ZipEntry entry = new ZipEntry(Path.GetFileName(fullPath));
The FAQ can be found here.
It seems to be a limitation of the library. Hope this helps!
If you have your files in a FileSystemInfo, you can use: z.Add(file.FullName, Path.GetFileName(file.FullName));
This will add your files in the root directory of your zip.
z.Add(pathToFile, pathInZipFile);

How to get a path from a directory in a C# console application?

Say I have this file structure
Soultion-> Folder1 -> FileIwant.html
So this could be something like C:\Soultion\Folder1\FilterIwant.html
Now I need to read this file into my application. I can't just hardcode it since when I give it to someone else they might put it on F: drive or something.
Or when I create a msi file the path might be completely different. So how can I say maybe take
"Folder1\FilterIwant.html"
and use that to get the folder path regardless of where they put it?
Edit
I tried Path.GetFullPath but I land up in the bin/debug directory. But my file is not in that directory. I think it is a couple directories before. Also if I make a msi file will I have bin/debug directory?
Why is a file which is used as part of your application not in the same folder as the application? It sounds to me like you should set the properties on that file to copy to the output folder when you do a build.
Doing that will make sure your file is in the bin\debug folder.
EDIT:
either that or you should be placing your files in one of the special folders, app data or my documents spring to mind.
When Visual Studio compiles your project, it will be putting the output into the bin\debug directory. Any content files that you want to reference must also be copied to those locations, in order for your app residing in that directory to be able to read that file.
You have two choices:
either you set the Copy to Output Directory property on your FilterIwant.html to Copy if newer; in that case, if the file has changed, it will be copied to the output directory, and you should be able to reference it and load it there
or
you just define a path in your app.config, something like DataPath, and set it to your folder where the file resides. From your app, you then create the full path name for that file as Path.Combine(AppSettings["DataPath"], "FilterIwant.html") - with this approach, you become totally independant of where the file really is and you don't need to move around anything. Also: this gives you the opportunity to create an admin/config utility for your users later on, so that they can pick any directory they like, and your app will find those files there.
In my console app, I started with the debug directory until i found the closest parent folder I wanted.
static void Main(string[] args)
{
Console.WriteLine("Start");
var debugDir = Environment.CurrentDirectory;
DirectoryInfo di = new DirectoryInfo(debugDir);
var searchDir = "";
while (!di.FullName.ToLower().EndsWith("Folder1"))
{
if(di.FullName.ToLower().EndsWith(":")) //if you went too far up as in "D:" then
break;
di = di.Parent;
}
Console.WriteLine(di.FullName);
}
You need the help of System.Io.Path class:
GetFullPath: Returns the absolute path for the specified path string.
Edit:
You might also need the application directory - this is where your application will be installed:
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
Path.GetFullPath
Edit
The bin/Debug path will not be present when you run your installed application (unless you specifically tell the installer to use that subdirectory, of course).
You probably want to pass the full path as a command line argument. You can then get the argument using the args parameter of the Main method. To convert a relative path to an absolute one you can use Path.GetFullPath:
using System;
using System.IO;
public class CommandLine
{
public static void Main(string[] args)
{
// The path is passed as the first argument
string fileName = arg[0];
// get absolute path
fileName = Path.GetFullPath(fileName);
// TODO: do whatever needs to done with the passed file name
}
}

Categories

Resources