Create directory - c#

I need to create a directory, but, the directory when I need to create is inside of another directory. Something like this:
Directory.CreateDirectory(#"teste\teste\teste\teste\");
basically, this directory does not exist ( of course ), but, the CreateDirectory(...) not support this string style, how I can make to create this directories ?
My way to make this is that:
private void createdir(string _path)
{
string path = string.Empty;
string[] dir = _path.Split('\\');
for(int i=0;i<dir.Length;i++)
{
path += dir[i] + "\\";
Directory.CreateDirectory(path);
}
}
But, I want to know, if have a more better way to make this ( a more legible ) more rapid.

Directory.Create("c:\teste\teste\teste\teste"); should workt

according to MSDN, you can nest the directory . CreateDirectory
Directory.CreateDirectory("Public\\Html");
Directory.CreateDirectory("\\Users\\User1\\Public\\Html");
Directory.CreateDirectory("c:\\Users\\User1\\Public\\Html"); // using verbatim string you can escape slashes
if(System.IO.Directory.Exists(yourPath))
{
Directory.CreateDirectory(yourPath);
}

Directory.CreateDirectory() can be used to create directories and subdirectories as specified by the path.
Here’s an example:
static void Main(string[] args)
{
try
{
Directory.CreateDirectory(#"D:\ParentDir\ChildDir\SubChildDir\");
Console.WriteLine("Directories Created");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Source

My chosen method would be:
DirectoryInfo di = new DirectoryInfo(#"teste\teste\teste\teste\");
di.Create();

Your way is too complicated for this process. You don't have to use Split() method also to create this kind of directories.
You can use it like;
string tempFolderAbsolutePath = #"C:\Temp";
string subFolderRelativePath = #"teste\teste\teste\teste\";
DirectoryInfo tempFolder = new DirectoryInfo( tempFolderAbsolutePath );
DirectoryInfo subFolder = tempFolder.CreateSubdirectory( subFolderRelativePath );
As you can see, this process creates nested subdirectories.

If your current directory is (say C:\) and you want to create a directory as C:\A\B\C, then I think the best way is using
Directory.CreateDirectory(#"\A\B\C");
If you need a directory in another root (say, D:\) then you need to give the full path as
Directory.CreateDirectory(#"D:\A\B\C");
You do not need to have a for loop to create each directory as CreateDirectory does it for you.

Related

How to get the Full Path of a File?

I try to get the Full Path of a File. ie. calc
Input: calc
Expected output: C:\WINDOWS\system32\calc.exe
I could find out how to do it with PowerShell:
(Get-Command calc).Source
Or with CommandLine:
where.exe calc
But unfortunately I can not get it done with C#.
The documentation for Get-Command says:
Get-Command * gets all types of commands, including all of the non-PowerShell files in the Path environment variable ($env:Path), which it lists in the Application command type.
So we will need to get the Path environment variable and iterate over the directories it lists, looking for files with extensions that indicate the file is a program, for example "*.com" and "*.exe".
The problem with the Path environment variable is that it can become polluted with non-existent directories, so we will have to check for those.
The case of the filename and extension don't matter, so case-insensitive comparisons need to be made.
static void ShowPath(string progName)
{
var extensions = new List<string> { ".com", ".exe" };
string envPath = Environment.GetEnvironmentVariable("Path");
var dirs = envPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string d in dirs.Where(f => Directory.Exists(f)))
{
foreach (var f in (Directory.EnumerateFiles(d).
Where(thisFile => extensions.Any(h => Path.GetExtension(thisFile).Equals(h, StringComparison.InvariantCultureIgnoreCase)))))
{
if (Path.GetFileNameWithoutExtension(f).Equals(progName, StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine(f);
return;
}
}
}
Console.WriteLine("Not found.");
}
static void Main(string[] args)
{
ShowPath("calc");
Console.ReadLine();
}
Output:
C:\WINDOWS\system32\calc.exe
There is always the possibility that the current user does not have permission to list the files from somewhere in the path, so checks should be added for that. Also, you might want to use StringComparison.CurrentCultureIgnoreCase for the comparison.
You can get the Pathenvironment variable, split it with ; as delimiter and loop over that result. Then, check if the file path + #"\" + name + ".exe" exists.
var findMe = "calc";
var pathes = Environment.GetEnvironmentVariable("Path").Split(';');
foreach (var path in pathes)
{
var testMe = $#"{path}\{findMe}.exe";
if (File.Exists(testMe))
{
Console.WriteLine(testMe);
}
}
This outputs :
C:\WINDOWS\system32\calc.exe
I do not know about any way of doing that exact thing from C# either. However the paths are usually well known and can be retreived via the SpecialFolders Enumeration:
using System;
using System.Diagnostics;
using System.IO;
namespace RunAsAdmin
{
class Program
{
static void Main(string[] args)
{
/*Note: Running a batch file (.bat) or similar script file as admin
Requires starting the interpreter as admin and handing it the file as Parameter
See documentation of Interpreting Programm for details */
//Just getting the Absolute Path for Notepad
string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
string FullPath = Path.Combine(windir, #"system32\notepad.exe");
//The real work part
//This is the programm to run
ProcessStartInfo startInfo = new ProcessStartInfo(FullPath);
//This tells it should run Elevated
startInfo.Verb = "runas";
//And that gives the order
//From here on it should be 100% identical to the Run Dialog (Windows+R), except for the part with the Elevation
System.Diagnostics.Process.Start(startInfo);
}
}
}
I did not just use System (37) back then, as I wrote it when x32/x86 Systems were still a thing. You would need to check how it resolves nowadays.
Note that most of those paths are duplicated in the PATH System Variable, so you could look it up: https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/
Path Variables in turn go back to the old DOS days. Basically if you gave the Commandline a command/filename it would try the build-in commands, then Executables in the current working Directory (.bat, .com, .exe), and then go look over the path directories to again look for executeables. And only if all that failed, would it complain.
I finally tried to combine all three answers and came up with this:
I post it here in case someone has the same problem.
public static string[] GetPathOf(string cmd)
{
var list = new List<string>();
list.AddRange(Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Machine).Split(';'));
list.AddRange(Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Process).Split(';'));
list.AddRange(Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.User).Split(';'));
list = list.Distinct().Where(e=>Directory.Exists(e)).SelectMany(e=> new DirectoryInfo(e).GetFiles()).Where(e=>Regex.IsMatch(e.Name,"(?i)^"+cmd+"\\.(?:exe|cmd|com)")).Select(e=>e.FullName).ToList();
return list.ToArray();
}

How can I quickly identify the path and the search pattern in C:\Users\Admin\Samples\*.pdf?

I would like to create a simple copy console application (I know copy already exists in DOS). Exactly like the DOS copy command I would like to be able to execute my copy application with two simple arguments:
copy C:\Users\Admin\Samples\*.pdf C:\
Input path and search pattern
Ouput path
In my code I use this
static void Main(string[] args)
{
string input;
string output;
var options = new Options();
ICommandLineParser parser = new CommandLineParser();
if (parser.ParseArguments(args, options))
{
input = options.Argument[0];
output = options.Argument[1];
// Get file list
String directory = Path.GetDirectoryName(input);
String[] files = Directory.GetFiles(directory, /* ??? */);
// To be continued...
}
else
{
System.Console.WriteLine("Erreur");
System.Console.ReadKey();
}
}
How can I easely retrieve my search pattern? Is beter way to do this?
Try this:
string extension = System.IO.Path.GetExtension(input);
string inputDirectory = System.IO.Path.GetDirectoryName(input);
I think this is what you wanted.
To get the path, or the file, of the input parameter, you can use the following:
Path.GetFileName(input);

Find the parent directory in c#

If path = "\ProgramFiles\MobileApp\es-gl\a.dll". I want to get "\ProgramFiles\MobileApp\es-gl" alone. Just want to know the parent directory of the file a.dll. Is there Any inbuilt method in c#? I am using .net Compact Framework
System.IO.Path.GetDirectoryName(path)
I also needed such a function to find the parent directory of a folder seamlessly. So I created one myself:
public static string ExtractFolderFromPath(string fileName, string pathSeparator, bool includeSeparatorAtEnd)
{
int pos = fileName.LastIndexOf(pathSeparator);
return fileName.Substring(0,(includeSeparatorAtEnd ? pos+1 : pos));
}
Just send pathSeparator ("\" for windows and "/" for unix-like paths).
set last parameter true if you want separator included at the end. for ex:
C:\foo\
I'm not sure but I think the FileInfo and DirectoryInfo classes are supported on the Compact Framework.
Try this:
FileInfo myFile = new FileInfo("\ProgramFiles\MobileApp\es-gl\a.dll");
string parentDirectory = myFile.Directory.Name;
According to the MSDN documentation you could also do this:
FileInfo myFile = new FileInfo("\ProgramFiles\MobileApp\es-gl\a.dll");
string parentDirectory = myFile.DirectoryName;
Check out these MSDN links for more info:
http://msdn.microsoft.com/en-us/library/system.io.fileinfo_members(v=vs.71)
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.directory(v=vs.71)
There is a Parent directory on FileInfo(System.IO namespace). Example code :
var file = new FileInfo(#"\ProgramFiles\MobileApp\es-gl\a.dll");
var parent = file.Directory.Parent;
You can just use the methods of the string class.
string path = #"\ProgramFiles\MobileApp\es-gl\a.dll";
string newPath = path.Substring(0, path.LastIndexOf('\\'));
var directory = Path.GetDirectoryName(#"c:\some\path\to\a\file.txt");
// returns "c:\some\path\to\a"
MSDN

If a folder does not exist, create it

I use a FileUploader control in my application. I want to save a file to a specified folder. If this folder does not exist, I want to first create it, and then save my file to this folder. If the folder already exists, then just save the file in it.
How can I do this?
Use System.IO.Directory.CreateDirectory.
According to the official ".NET" docs, you don't need to check if it exists first.
System.io   >   Directory   >   Directory.CreateDirectory
Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. If the directory already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory.
        — learn.microsoft.com/dotnet/api/
Use the below code as per How can I create a folder dynamically using the File upload server control?:
string subPath ="ImagesPath"; // Your code goes here
bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));
if(!exists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
Just write this line:
System.IO.Directory.CreateDirectory("my folder");
If the folder does not exist yet, it will be created.
If the folder exists already, the line will be ignored.
Reference: Article about Directory.CreateDirectory at MSDN
Of course, you can also write using System.IO; at the top of the source file and then just write Directory.CreateDirectory("my folder"); every time you want to create a folder.
Directory.CreateDirectory explains how to try and to create the FilePath if it does not exist.
Directory.Exists explains how to check if a FilePath exists. However, you don't need this as CreateDirectory will check it for you.
You can create the path if it doesn't exist yet with a method like the following:
using System.IO;
private void CreateIfMissing(string path)
{
bool folderExists = Directory.Exists(Server.MapPath(path));
if (!folderExists)
Directory.CreateDirectory(Server.MapPath(path));
}
This method will create the folder if it does not exist and do nothing if it exists:
Directory.CreateDirectory(path);
You can use a try/catch clause and check to see if it exist:
try
{
if (!Directory.Exists(path))
{
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
}
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
using System.IO
if (!Directory.Exists(yourDirectory))
Directory.CreateDirectory(yourDirectory);
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
The following code is the best line(s) of code I use that will create the directory if not present.
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/temp/"));
If the directory already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory. >
Create a new folder, given a parent folder's path:
string pathToNewFolder = System.IO.Path.Combine(parentFolderPath, "NewSubFolder");
DirectoryInfo directory = Directory.CreateDirectory(pathToNewFolder);
// Will create if does not already exist (otherwise will ignore)
path to new folder given
directory information variable so you can continue to manipulate it as you please.
Use this code if the folder is not presented under the image folder or other folders
string subPath = HttpContext.Current.Server.MapPath(#"~/Images/RequisitionBarCode/");
bool exists = System.IO.Directory.Exists(subPath);
if(!exists)
System.IO.Directory.CreateDirectory(subPath);
string path = HttpContext.Current.Server.MapPath(#"~/Images/RequisitionBarCode/" + OrderId + ".png");
Use the below code. I use this code for file copy and creating a new folder.
string fileToCopy = "filelocation\\file_name.txt";
String server = Environment.UserName;
string newLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\file_name.txt";
string folderLocation = "C:\\Users\\" + server + "\\Pictures\\Tenders\\";
bool exists = System.IO.Directory.Exists(folderLocation);
if (!exists)
{
System.IO.Directory.CreateDirectory(folderLocation);
if (System.IO.File.Exists(fileToCopy))
{
MessageBox.Show("file copied");
System.IO.File.Copy(fileToCopy, newLocation, true);
}
else
{
MessageBox.Show("no such files");
}
}
A fancy way is to extend the FileUpload with the method you want.
Add this:
public static class FileUploadExtension
{
public static void SaveAs(this FileUpload, string destination, bool autoCreateDirectory) {
if (autoCreateDirectory)
{
var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));
if (!destinationDirectory.Exists)
destinationDirectory.Create();
}
file.SaveAs(destination);
}
}
Then use it:
FileUpload file;
...
file.SaveAs(path,true);
string root = #"C:\Temp";
string subdir = #"C:\Temp\Mahesh";
// If directory does not exist, create it.
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
The CreateDirectory is also used to create a sub directory. All you have to do is to specify the path of the directory in which this subdirectory will be created in. The following code snippet creates a Mahesh subdirectory in C:\Temp directory.
// Create sub directory
if (!Directory.Exists(subdir))
{
Directory.CreateDirectory(subdir);
}
Derived/combined from multiple answers, implementing it for me was as easy as this:
public void Init()
{
String platypusDir = #"C:\platypus";
CreateDirectoryIfDoesNotExist(platypusDir);
}
private void CreateDirectoryIfDoesNotExist(string dirName)
{
System.IO.Directory.CreateDirectory(dirName);
}

Check if DirectoryInfo.FullName is special folder

My goal is to check, if DirectoryInfo.FullName is one of the special folders.
Here is what I'm doing for this (Check directoryInfo.FullName to each special folder if they are equal):
DirectoryInfo directoryInfo = new DirectoryInfo("Directory path");
if (directoryInfo.FullName == Environment.GetFolderPath(Environment.SpecialFolder.Windows) ||
directoryInfo.FullName == Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles ||)
...
...
)
{
// directoryInfo is the special folder
}
But there are many special folders (Cookies, ApplicationData, InternetCache, etc.). Is there any way to do this task more efficiently?
Thanks.
Try this following code :
bool result = false;
DirectoryInfo directoryInfo = new DirectoryInfo("Directory path");
foreach (Environment.SpecialFolder suit in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
if (directoryInfo.FullName == Environment.GetFolderPath(suit))
{
result = true;
break;
}
}
if (result)
{
// Do what ever you want
}
hope this help.
I'm afraid the answers given seem to be the only way, I hate the special folders because what ought to be a very simple function -
void CollectFiles(string strDir, string pattern) {
DirectoryInfo di = new DirectoryInfo(strDir);
foreach(FileInfo fi in di.GetFiles(pattern) {
//store file data
}
foreach(DirectoryInfo diInfo in di.GetDirectories()) {
CollectFiles(diInfo);
}
}
Becomes ugly because you have to include
Check If This Is A Special Folder And Deal With It And Its Child Folders Differently ();
Fair enough Microsoft, to have a folder that could exist anywhere, on a remote PC, on a server etc. But really what is wrong with the UNIX/Linux way, use links to folder and if the destination physical folder has to move, alter the link. Then you can itterate them in a nice neat function treating them all as if ordinary folders.
I don't have enough reputation to add a comment so as a +1 to BobRassler's answer, string comparisons might be more useful.
bool isSpecialFolder = false;
DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(tbx_FolderName.Text, fileName));
foreach (Environment.SpecialFolder specialFolder in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
if (directoryInfo.FullName.ToString()
.ToLower() ==
Environment.GetFolderPath(specialFolder)
.ToLower())
{
isSpecialFolder = true;
break;
}
}
if (isSpecialFolder)
{
// something
}
else
{
// something else
}
Use a reflection to get all values from that enum, like here http://geekswithblogs.net/shahed/archive/2006/12/06/100427.aspx and check against collection of generated paths you get.
I ended up using it this way:
public static bool IsSpecialFolder(DirectoryInfo directoryInfo, out Environment.SpecialFolder? _specialFolder) {
bool isSpecialFolder = false;
_specialFolder = null;
string directoryInfo_FullPath = directoryInfo.FullName;
foreach (Environment.SpecialFolder specialFolder in Enum.GetValues(typeof(Environment.SpecialFolder))) {
var specialFolder_FullPath = Environment.GetFolderPath(specialFolder);
if (string.Equals(directoryInfo_FullPath, specialFolder_FullPath, StringComparison.OrdinalIgnoreCase)) {
isSpecialFolder = true;
_specialFolder = specialFolder;
break;
}
}
return isSpecialFolder;
}
If handling strings from dubious sources (the user :-) ), there are three caveats to keep in mind:
Path.Combine vs. Path.Join, since they handle absolute paths (or paths that look like absolute paths) differently.
Path.GetFullPath, which takes a string an produces the full and normalized version of it.
GetFolderPath can return an empty string, which generates a System.ArgumentException: 'The path is empty. (Parameter 'path')' when used for creating a DirectoryInfo.
I like to keep this logic outside the method, but I am not sure if the OrdinalIgnoreCase or any other normalization is still necessary. I guess not.
P.S.: I think in modern lingo the method should be called TrySpecialFolder or something :-)

Categories

Resources