DirectoryInfo usage in a UWP project - c#

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");
}
}

Related

Compare local and remote files using WinSCP .NET assembly

I'm trying to implement some logic to compare file information between remote server and local server.
I need to compare the file name between local folder and remote folder and download only the new files.
I tried using loading files in a list and use Except function, it didn't work.
Appreciate your help.
Please find one of the scenario I tried.
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
const string remotePath = "/Test";
const string localPath = #"C:\Local";
const string ArchivePath = #"C:\Users\Local\Archive";
System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(ArchivePath);
RemoteDirectoryInfo dir1 = session.ListDirectory(remotePath);
IEnumerable<System.IO.FileInfo> list2 =
dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
IEnumerable<RemoteFileInfo> list1 =
session.EnumerateRemoteFiles(remotePath, "*.csv", EnumerationOptions.None);
var firstNotSecond = list1.Except(list2).ToList();
}
Getting error like
'IEnumerable' does not contain a definition for 'Except' and the best extension method overload 'Queryable.Except(IQueryable, IEnumerable)' requires a receiver of type 'IQueryable'
You will have to compare just the filenames:
var firstNotSecond =
list1.Select(_ => _.Name).Except(list2.Select(_ => _.Name)).ToList();
Though note that WinSCP .NET has this functionality built-in. There's Session.CompareDirectories.
And if you actually want to synchronize the directories, there's Session.SynchronizeDirectories. One method that will do everything for you.
session.SynchronizeDirectories(
SynchronizationMode.Local, localPath, remotePath, false).Check()

How can I access a local folder inside a WPF project to load and store files?

I need a library of vector files, where the same files have to be used every time. I want to load them from a folder and have the option to store new ones.
I tried having a library folder inside the WPF project that contains the files:
Solution/Project/Library/file1.dxf
I load them like this:
string currentDir = Directory.GetCurrentDirectory();
var cutOff = currentDir.LastIndexOf(#"\bin\");
var folder = currentDir.Substring(0, cutOff) + #"\Library\";
string[] filePaths = Directory.GetFiles(folder, "*.dxf");
This worked when running on the PC the project was buid, but the program crashes when the .exe is run on another PC. How do I fix this or is there a better approach to this?
Create a subfolder under Environment.SpecialFolder.ApplicationData, read the files in the library folder if it exists. If not create it and save the existing library files to it (here from resources):
string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appFolder + #"\MyAppLibrary\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// Add existing files to that folder
var rm = Properties.Resources.ResourceManager;
var resSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (var res in resSet)
{
var entry = ((DictionaryEntry)res);
var name = (string)entry.Key;
var file = (byte[])rm.GetObject(name);
var filePath = path + name + ".dxf";
File.WriteAllBytes(filePath, file);
}
}
// Load all files from the library folder
string[] filePaths = Directory.GetFiles(path, "*.dxf");
Thanks Jonathan Alfaro and Clemens!

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");

How to get parent directory in a path c#?

it is my path example E:\test\img\sig.jpg
I want to get E:\test\img to create directory
i try split but it be img
so I try function Directory.CreateDirectory and the path is E:\test\img\sig.jpg\
say me a ideas?
The recommended way is to use Path.GetDirectoryName():
string file = #"E:\test\img\sig.jpg";
string path = Path.GetDirectoryName(file); // results in #"E:\test\img"
Use Path.GetDirectoryName which returns the directory information for the specified path string.
string directoryName = Path.GetDirectoryName(filePath);
The Path class contains a lot of useful methods for path handling, which are more reliable than manual string manipulation:
var directoryComponent = Path.GetDirectoryName(#"E:\test\img\sig.jpg");
// yields `E:\test\img`
For completeness, I'd like to mention Path.Combine, which does the opposite:
var dirAndFile = Path.Combine(#"E:\test\img", "sig.jpg");
// no more checking for trailing slashes, hooray!
To create the directory, you can use Directory.Create. Note that it is not necessary to check if the directory exists first.
You can try this code to find the directory name.
System.IO.FileInfo fi = new System.IO.FileInfo(#"E:\test\img\sig.jpg");
string dirname = fi.DirectoryName;
and to create the directory
Directory.CreateDirectory(dirname );
Another solution can be :
FileInfo f = new FileInfo(#"E:\test\img\sig.jpg");
if (f.Exists)
{
string dirName= f.DirectoryName;
}

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);
}

Categories