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");
Related
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");
}
}
Pretty straight forward. Press a button, select a path from dialogbox, searches path's subdirectories, and shows them in messagebox. But have ran into a couple problems.
private void InputButton_Click(object sender, RoutedEventArgs e)
{
//CHECKS TO SEE IF "OK" WAS CLICKED IN DIALOGBOX
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
//SELECTS DIRECTORY PATH
Path.GetDirectoryName(fbd.SelectedPath);
string path = Path.GetDirectoryName(fbd.SelectedPath);
InputDirectory_Box.Text = path;
//SELECTS SUBDIRECTORIES FROM PATH
string[] subdirectories = DirectoryInfo.GetDirectories(path);
for (int i = 0; subdirectories.Length+1 >= 0; i++)
{
MessageBox.Show(subdirectories[i]);
}
}
The line string[] subdirectories = DirectoryInfo.GetDirectories(path); says it needs an object reference for the non-static field. I've already declared path to give it the string to search. I used this exact same line of code and syntax for the Directory class (not the DirectoryInfo class) and it was legal. However, i was having a problem when using Directory.GetDirectories. It was finding the path's parent directories instead of the subdirectories for some reason.
If anyone could shine some light on:
A - why I'm getting this syntax error
B - why it was returning parent directories instead of sub-directories from the path
Then you would be a hero. Many thanks
PS I'm completely new to programming and don't know what enumerating/enumeration is quite yet so if it has something to do with that, I'd appreciate maybe a small example or some context of what it is.
GetDirectories is an instance method. You need to have an instance of DirectoryInfo to use it.
string path = fbd.SelectedPath;
// Make a reference to a directory.
DirectoryInfo di = new DirectoryInfo(path);
// Get a reference to each directory in that directory.
string[] subdirectories = di.GetDirectories();
The static class would be Directory
Directory.GetDirectories(path);
The first of those two lines is useless...
Path.GetDirectoryName(fbd.SelectedPath);
string path = Path.GetDirectoryName(fbd.SelectedPath);
Next thing: I do not understand that loop... what do you want to achieve with Length+1>=0?
To print out all directories of any list/array you have two choices: A for loop, or even better if you don't need the index of the items, a foreach loop.
Look at these examples:
string[] subdirectories = Directory.GetDirectories(path);
for (int i = 0; i < subdirectories.Length; i++)
{
MessageBox.Show(subdirectories[i]);
}
string[] subdirectories = Directory.GetDirectories(path);
foreach (string directory in subdirectories)
{
MessageBox.Show(directory);
}
hope this helps.
Ok so this is my issue currently:
This is my main:
//System prompts user the type of archiving which will direct to the correct directory to set as root
Console.WriteLine("Enter the type of archiving you would like to do?");
string archivetype = Console.ReadLine();
//function that identifies which candidates to archive
Archive(archivetype, 20, 20);
//keep the application in debug mode
Console.ReadKey();
The archive method:
//Archive method determines which directory to search in and how many versions to archive
static void Archive(string archivetype, int pversion, int version)
{
//regex pattern to get folder names of the type #.#.#.#/#. something
Regex reg = new Regex(#"\d+(\.\d+)+");
//setting where to start looking
DirectoryInfo root = new DirectoryInfo(#"C:\Users\jphillips\Desktop\test\parent\ACE-3_0");
var dirs = new List<DirectoryInfo>();
//i want to make a recursive call to all the folders in my root directory to obtain all the folders with the regex pattern above that are not empty and do not have 3 files inside
WalkDirectoryTree(root);
}
finally walk directorytree method
//so im using the walk directory tree on the microsoft website i need a way to have a sort of a global array to keep adding the directories that fit through the patterns mentioned above without resetting itself after each walkdirectorytree call
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
DirectoryInfo[] subDirs = null;
// Now find all the subdirectories under this root directory.
subDirs = root.GetDirectories();
foreach (DirectoryInfo dir in subDirs)
{
//dirs is not global so it doesnt work here and i believe if i put a local array that it will reset itself everytime
dirs = root.GetDirectories("*", SearchOption.TopDirectoryOnly).Where(d => reg.IsMatch(d.Name)).ToList();
if()
WalkDirectoryTree(dir);
}
}
so im really lost at this point I want to able to call walkdirectorytree to go through all my folders and subfolders of my directory recursevely to extrract the paths that have the regex pattern and that are not empty and do not have 3 files inside tp give me a list of these folders paths.
You can get all the folders and subfolders in a single call with this overload of GetDirectories.
You pass in a search string - but not a regex unfortunately and SearchOption.AllDirectories as the second argument. You can then pass the results through your regex to find the ones you are interested in.
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
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);
}