Cannot Create Directory error - c#

I am trying to create a directory if it does not exist. It correctly goes into the code to create the directory because it doesn't exist. But then it gives me the following error:
DirectoryNotFoundException was unhandled
Could not find part of the path "\192.168.22.2\2009"
var fileYear = createdDate.Value.Year.ToString();
var fileMonth = createdDate.Value.Month.ToString();
var rootDir = #"\\192.168.22.2";
if (!File.Exists(Path.Combine(rootDir,fileYear)))
{
// Create the Year folder
Directory.CreateDirectory(Path.Combine(rootDir,fileYear));
}

You need to have a share name after the #"\\192.168.22.2".
Something like #"\\192.168.22.2\MySharedFolder".
You cannot create a subfolder from that root dir

Related

trying to get random file but getting System.IO.DirectoryNotFoundException instead

I'm new to programming so please don't be mean to me...
I'm trying to get a random file from random folder but System.IO.DirectoryNotFoundException keeps showing up.
I used codes from these answers
https://stackoverflow.com/a/2533731/10297934
https://stackoverflow.com/a/742690/10297934
This is my code.
DirectoryInfo[] subDirs;
DirectoryInfo root;
root = new DirectoryInfo(#"E:\items\");
subDirs = root.GetDirectories();
Random random = new Random();
int directory = random.Next(subDirs.Length);
DirectoryInfo randomDirectory = subDirs[directory];
var files = Directory.GetFiles(randomDirectory.ToString(), "*.jpg");
//this is where i get exception
var pictureToDisplay = files[random.Next(files.Length)];
pbxDateV.Image = Image.FromFile(pictureToDisplay);
And this is the exception i get
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\erica\source\repos\1\1\bin\Debug\forge'.'
"forge" is indeed one of name of folder from "items". The exception message showed me other random folder name each time it shows up so the code is working in some way but I'm not sure why bin folder is selected as a path.
randomDirectory.ToString() doesn't return full path, it rather returns the Folder Name alone. So the Directory.GetFiles checks in the current working directory, which is the execution Directory of the application.
You should use DirectoryInfo.FullName instead.
var files = Directory.GetFiles(randomDirectory.FullName, "*.jpg");
//this is where i get exception
var pictureToDisplay = files[random.Next(files.Length)];
The problem in your code is at below line -
var files = Directory.GetFiles(randomDirectory.ToString(), "*.jpg");
Because subDirs only stores the name of subdirectories not the full path, when above line get executes it tries to find that folder in your current code working directory. So either you use randomDirectory.FullName or append root with randomdirectory as below -
var files = Directory.GetFiles(randomDirectory.ToString(), "*.jpg");

DirectoryInfo usage in a UWP project

I am currently working to a Windows 10 UWP project and I keep getting the following exception:
Unable to cast object of type 'System.IO.FileSystemInfo[]' to type 'System.Collections.Generic.IEnumerable`1[System.IO.FileInfo]'.
and this is the code which throws it:
DirectoryInfo dirInfo = new DirectoryInfo(path);
FileInfo[] files = dirInfo.GetFiles(path);
path is a valid one, i verified it several times, I do not know why I am getting this exception. Can the DirectoryInfo class still be used in a UWP application or should I use an equivalent one ?
The DirectoryInfo class is applicable for UWP. However, it has a lot of limitations. Such as whether the path is valid. For more detail you could refer to Skip the path: stick to the StorageFile.
It throw Second path fragment must not be a drive or UNC name exception when I passed path parameter. I found the following description.
The search string to match against the names of files. This parameter can contain
a combination of valid literal path and wildcard (* and ?) characters (see Remarks),
but doesn't support regular expressions. The default pattern is "*", which returns
all files.
So I modify the searchPattern like the following, it works well.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + #"\Assets\Media";
DirectoryInfo dirinfo = new DirectoryInfo(path);
FileInfo[] files = dirinfo.GetFiles("head.*");
I do not know why I am getting this exception. Can the DirectoryInfo class still be used in a UWP application or should I use an equivalent one ?
The best practice to query files in UWP is to use folder picker to select a folder and enumerate all the files with GetFilesAsync method. For example:
var picker = new Windows.Storage.Pickers.FolderPicker();
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add("*");
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
var folder = await picker.PickSingleFolderAsync();
if(folder != null)
{
StringBuilder outputText = new StringBuilder();
var query = folder.CreateFileQuery();
var files = await query.GetFilesAsync();
foreach (StorageFile file in files)
{
outputText.Append(file.Name + "\n");
}
}

How to navigate one folder up from current file path?

I need to navigate one folder up from the current path of a file and save the same file there. How can I strip one level from the directory path? Thank you!
C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf
The file will be saved to below.
C:\Users\stacy.zim\AppData\Local\Temp\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf
Actually it is called Parent for "One Folder Up"
System.IO.DirectoryInfo.Parent
// Method 1 Get by file
var file = new FileInfo(#"C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf");
var parentDir = file.Directory == null ? null : file.Directory.Parent; // null if root
if (parentDir != null)
{
// Do something with Path.Combine(parentDir.FullName, filename.Name);
}
System.IO.Directory.GetParent()
// Method 2 Get by path
var parentDir = Directory.GetParent(#"C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\");
string path = #"C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf"
string directory = Path.GetDirectoryName(path); //without file name
string oneUp = Path.GetDirectoryName(directory); // Temp folder
string fileOneUp = Path.Combine(oneUp, Path.GetFileName(path));
Just be careful if the original file is in root folder - then the oneUp will be null and Path.Combine will throw an exception.
Edit:
In the code above, I split the commands on separate lines for clarity. It could be done in one line:
Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), Path.GetFileName(path));
Or, as #AlexeiLevenkov suggest, you can use .. to go up one directory. In that case, you could do:
Path.Combine(Path.GetDirectoryName(path), #"..\"+Path.GetFileName(path));
which will give you the .. in your path - if you don't want that, run Path.GetFullPath on the result. Again, you need to be careful if your original file is in the root folder - unlike the first approach, which will throw an exception, this will just give you the same path.

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 can get the current virtual path without file name?

Request.Path will get the current Path name with file name such as:
C:/......./Personal/Items.aspx
How can I get the only Path name such as:
C:/......./Personal
You can use Path.GetDirectoryName to get the directory part of a path.
var path = System.IO.Path.GetDirectoryName(#"C:\Personal\Items.aspx");
// path is #"C:\Personal"
This will return the virtual path:
Page.TemplateSourceDirectory
See the below answers for the physical path.
Use the GetParent() method on Directory.
DirectoryInfo parent = Directory.GetParent(requestPath);
you can get Directory Path from System.IO.FileInfo
var fInfo = new System.IO.FileInfo(path);
var result = fInfo.DirectoryName;

Categories