Whats the code to create a directory if it doesnt exist? - c#

I am having a problem with coding my save-directory. I want it to create a folder called "Ausgabe" (Output) on the current users Desktop, but I do not know how to check if it already exists and if it doesn't then create it.
This is my current code for that part so far:
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// need some code here
}
What do I add in order to make it do what I want it to do?

You can check if a directory exists using
Directory.Exists(pathToDirectory)
and create a directory using
Directory.CreateDirectory(pathToDirectory)
EDIT In response to your comment:
string directoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Ausgabe")
should give you the path to a folder named 'Ausgabe' in the users Desktop-folder.

Just use Directory.CreateDirectory. If the directory exists the method will not create it (in other words it contains a call to Directory.Exists internally)
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
public Form1()
{
string myFolder = Path.Combine(path, "Ausgabe");
Directory.CreateDirectory(myFolder);
}
To use this method you need to add a using System.IO to the top of your Form1.cs file.
I wish also to say that the Desktop is not the most appropriate place to create a directory for your application. There is a proper place provided by the System and it is under the ProgramData enum (CommonApplicationData or ApplicationData)
string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

As per this doc, the Directory.CreateDirectory Method (String) will
Creates all directories and subdirectories in the specified path
unless they already exist.
So it is fine to use like this:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string desktopFolder = Path.Combine(path, "New Folder");
Directory.CreateDirectory(desktopFolder);

You can use the Directory.Exists() method: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx
Your code would propebly look something like this:
public static void Main()
{
// Specify the directory you want to manipulate.
string path = #"c:\MyDir";
try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
Console.WriteLine("That path exists already.");
return;
}
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
// Delete the directory.
di.Delete();
Console.WriteLine("The directory was deleted successfully.");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}

I have had a recent issue so here is my solution,
I had to find the deployed directory
var deployedDir = Assembly.GetEntryAssembly().CodeBase;
deployedDir = Path.GetDirectoryName(deployedDir);
deployedDir = deployedDir.Replace("file:\\", "");
var pathToDirectory= Path.Combine(deployedDir, "YourFileName");
Then do what the above answers show and create the directory if it doesnt exist,
Directory.CreateDirectory(pathToDirectory)

Related

Copying an image file to an empty folder in using WPF C#

After going through all the related stuff to copying files i am unable to find an answer to my
problem of an exception occurring while i was trying to copy a file to an empty folder in WPF application. Here is the code snippet.
public static void Copy()
{
string _finalPath;
foreach (var name in files) // name is the filename extracted using GetFileName in a list of strings
{
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if(System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath,name);
System.IO.File.Copy(name, _finalPath , true);
}
}
}
While debugging exception is occuring at file.copy() statement which says
"FileNotFoundException was unhandled" could not find file
i already know about the combining path and other aspects of copy but i dont know why this exception is being raised.
I am a noob to WPF please help.........
Use following code:
public static void Copy()
{
string _finalPath;
var files = System.IO.Directory.GetFiles(#"C:\"); // Here replace C:\ with your directory path.
foreach (var file in files)
{
var filename = file.Substring(file.LastIndexOf("\\") + 1); // Get the filename from absolute path
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if (System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath, filename);
System.IO.File.Copy(file, _finalPath, true);
}
}
}
The GetFileName ()
only returns the actual name of the file (drops the path) what you want is a full path to the file. So you getting an exception because the 'name' does not exist on your drive (path is unknown)
You're variable, name, is most likely just the file name (i.e. something.jpg). When you use the File.Copy(...) method, if you do not supply an absolute path the method assumes a path relative to the executable.
Basically, if you are running your app in, for example, C:\Projects\SomeProject\bin\Debug\SomeProject.exe, then it is assuming your file is C:\Projects\SomeProject\bin\Debug\something.jpg.

Moving files based on name to the corresponding folder

Hello everyone and well met! I have tried a lot of different methods/programs to try and solve my problem. I'm a novice programmer and have taken a Visual Basic Class and Visual C# class.
I'm working with this in C#
I started off by making a very basic move file program and it worked fine for one file but as I mentioned I will be needing to move a ton of files based on name
What I am trying to do is move .pst (for example dave.pst) files from my exchange server based on username onto a backup server in the users folder (folder = dave) that has the same name as the .pst file
The ideal program would be:
Get files from the folder with the .pst extension
Move files to appropriate folder that has the same name in front of the .pst file extension
Update:
// String pstFileFolder = #"C:\test\";
// var searchPattern = "*.pst";
// var extension = ".pst";
//var serverFolder = #"C:\test3\";
// String filename = System.IO.Path.GetFileNameWithoutExtension(pstFileFolder);
// Searches the directory for *.pst
DirectoryInfo sourceDirectory = new DirectoryInfo(#"C:\test\");
String strTargetDirectory = (#"C:\test3\");
Console.WriteLine(sourceDirectory);
Console.ReadKey(true);>foreach (FileInfo file in sourceDirectory.GetFiles()) {
Console.WriteLine(file);
Console.ReadKey(true);
// Try to create the directory.
System.IO.Directory.CreateDirectory(strTargetDirectory);
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}
This is just a simple copy procedure. I'm completely aware. The
Console.WriteLine(file);
Console.ReadKey(true);
Are for verification purpose right now to make sure I'm getting the proper files and I am. Now I just need to find the folder based on the name of the .pst file(the folder for the users are already created), make a folder(say 0304 for the year), then copy that .pst based on the name.
Thanks a ton for your help guys. #yuck, thanks for the code.
Have a look at the File and Directory classes in the System.IO namespace. You could use the Directory.GetFiles() method to get the names of the files you need to transfer.
Here's a console application to get you started. Note that there isn't any error checking and it makes some assumptions about how the files are named (e.g. that they end with .pst and don't contain that elsewhere in the name):
private static void Main() {
var pstFileFolder = #"C:\TEMP\PST_Files\";
var searchPattern = "*.pst";
var extension = ".pst";
var serverFolder = #"\\SERVER\PST_Backup\";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, searchPattern)) {
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Gets the user name based on file name
// e.g. DaveSmith.pst would become DaveSmith
var userName = theFileInfo.Name.Replace(extension, "");
// Sets up the destination location
// e.g. \\SERVER\PST_Backup\DaveSmith\DaveSmith.pst
var destination = serverFolder + userName + #"\" + theFileInfo.Name;
File.Move(file, destination);
}
}
System.IO is your friend in this case ;)
First, Determine file name by:
String filename = System.IO.Path.GetFileNameWithoutExtension(SOME_PATH)
To make path to new folder, use Path.Combine:
String targetDir = Path.Combine(SOME_ROOT_DIR,filename);
Next, create folder with name based on given fileName
System.IO.Directory.CreateDirectory(targetDir);
Ah! You need to have name of file, but with extension this time. Path.GetFileName:
String fileNameWithExtension = System.IO.Path.GetFileName(SOME_PATH);
And you can move file (by File.Move) to it:
System.IO.File.Move(SOME_PATH,Path.Combine(targetDir,fileNameWithExtension)
Laster already show you how to get file list in folder.
I personally prefer DirectoryInfo because it is more object-oriented.
DirectoryInfo sourceDirectory = new DirectoryInfo("C:\MySourceDirectoryPath");
String strTargetDirectory = "C:\MyTargetDirectoryPath";
foreach (FileInfo file in sourceDirectory.GetFiles())
{
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}

How to move txt file to other folder?

I try to write a console app C# to move my etxt files to another folder.
The functions just copies certain .txt files from folder A to folder AA
string source = "C:\\A\\ResultClassA.txt";
File.Move(Source, "C:\\AA");
But its always giving this error message:
Access to the path is denied.
Troubleshooting tips:
Make sure you have sufficient privileges to access this resource.
If you are attempting to access a file, make sure it is not ReadOnly.
Get general help for this exception.
Do i really need to set my folder A and folder B to "NOT ReadOnly" attribute before "File.move" code are execuse? and set to read only back after success moved?
Thanks.
By Hero .
You need to specify the full path and make sure the path C:\AA exists
string source = "C:\\A\\ResultClassA.txt";
File.Move(Source, "C:\\AA\\ResultClassA.txt");
See here for good sample
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
string path2 = #"c:\temp2\MyTest.txt";
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) {}
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
Console.WriteLine("{0} was moved to {1}.", path, path2);
// See if the original exists now.
if (File.Exists(path))
{
Console.WriteLine("The original file still exists, which is unexpected.");
}
else
{
Console.WriteLine("The original file no longer exists, which is expected.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
Hero, you are moving from a file name to a folder name, try to specify a file name with extension inside the C:\AA folder.
does AA exist already on C ?

C# folders and sub folders

How to do this:
Check if folder upload exists (if nor then create it) ~/ uploads
Check if subfolder with username exists ~/uploads/folder with username
It as to check for each case individually because I could add a new user to the system and of course the folder uploads alredy exists, just need to create a sub folder with username
In short:
Use HttpServerUtility.MapPath to convert the virtual path (such as ~/uploads) to a physical path.
Use Directory.Exists to determine if the directory exists or not
If the directory does not exist, use Directory.CreateDirectory to create it.
string userName = ""; // Substitute with logic for obtaining username
string folder = ResolveUrl( "~/Uploads" );
folder = System.IO.Path.Combine( folder, userName );
if ( !System.IO.Directory.Exists( folder ) )
System.IO.Directory.CreateDirectory( folder );
try this:
var path = string.Format(#"{0}Uploads\{1}",Request.PhysicalApplicationPath,
HttpContext.Current.User.Identity.Name);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
You could try this :
using System;
using System.IO;
public void CreateDirectories(string uploadDirPath, string userName)
{
string userDirPath= uploadDirPath + "\\" + userName ;
if (!Directory.Exists(uploadDirPath))
{
Directory.CreateDirectory(uploadDirPath);
if (!Directory.Exists(userDirPath))
Directory.CreateDirectory (userDirPath);
}
}
I leave it to you to wrap this up by calling the method in loops according to you specific logic and paramaterizing user names and folders

How do I create a file AND any folders, if the folders don't exist?

Imagine I wish to create (or overwrite) the following file :- C:\Temp\Bar\Foo\Test.txt
Using the File.Create(..) method, this can do it.
BUT, if I don't have either one of the following folders (from that example path, above)
Temp
Bar
Foo
then I get an DirectoryNotFoundException thrown.
So .. given a path, how can we recursively create all the folders necessary to create the file .. for that path? If Temp or Bar folders exists, but Foo doesn't... then that is created also.
For simplicity, lets assume there's no Security concerns -- all permissions are fine, etc.
To summarize what has been commented in other answers:
//path = #"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));
Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.
If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
Directory.GetCreationTime(path));
See this MSDN page.
Use Directory.CreateDirectory before you create the file. It creates the folder recursively for you.
. given a path, how can we recursively create all the folders necessary to create the file .. for that path
Creates all directories and subdirectories as specified by path.
Directory.CreateDirectory(path);
then you may create a file.
You will need to check both parts of the path (directory and filename) and create each if it does not exist.
Use File.Exists and Directory.Exists to find out whether they exist. Directory.CreateDirectory will create the whole path for you, so you only ever need to call that once if the directory does not exist, then simply create the file.
You should use Directory.CreateDirectory.
http://msdn.microsoft.com/en-us/library/54a0at6s.aspx
Assuming that your assembly/exe has FileIO permission is itself, well is not right. Your application may not run with admin rights. Its important to consider Code Access Security and requesting permissions
Sample code:
FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
f2.Demand();
}
catch (SecurityException s)
{
Console.WriteLine(s.Message);
}
Understanding .NET Code Access Security
Is “Code Access Security” of any real world use?
You want Directory.CreateDirectory()
Here is a class I use (converted to C#) that if you pass it a source directory and a destination it will copy all of the files and sub-folders of that directory to your destination:
using System.IO;
public class copyTemplateFiles
{
public static bool Copy(string Source, string destination)
{
try {
string[] Files = null;
if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
destination += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(destination)) {
Directory.CreateDirectory(destination);
}
Files = Directory.GetFileSystemEntries(Source);
foreach (string Element in Files) {
// Sub directories
if (Directory.Exists(Element)) {
copyDirectory(Element, destination + Path.GetFileName(Element));
} else {
// Files in directory
File.Copy(Element, destination + Path.GetFileName(Element), true);
}
}
} catch (Exception ex) {
return false;
}
return true;
}
private static void copyDirectory(string Source, string destination)
{
string[] Files = null;
if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) {
destination += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(destination)) {
Directory.CreateDirectory(destination);
}
Files = Directory.GetFileSystemEntries(Source);
foreach (string Element in Files) {
// Sub directories
if (Directory.Exists(Element)) {
copyDirectory(Element, destination + Path.GetFileName(Element));
} else {
// Files in directory
File.Copy(Element, destination + Path.GetFileName(Element), true);
}
}
}
}
Following code will create directories (if not exists) & then copy files.
// using System.IO;
// for ex. if you want to copy files from D:\A\ to D:\B\
foreach (var f in Directory.GetFiles(#"D:\A\", "*.*", SearchOption.AllDirectories))
{
var fi = new FileInfo(f);
var di = new DirectoryInfo(fi.DirectoryName);
// you can filter files here
if (fi.Name.Contains("FILTER")
{
if (!Directory.Exists(di.FullName.Replace("A", "B"))
{
Directory.CreateDirectory(di.FullName.Replace("A", "B"));
File.Copy(fi.FullName, fi.FullName.Replace("A", "B"));
}
}
}

Categories