Im looking for a way to find all files in an shared special folder (Virtual Folder).
The Desktop for example is an shared folder, there is a public Desktop for all users and a private Desktop. By navigating with the file explorer to Desktop you will see the contents of both desktops merged together.
Example:
Shared folder for all:
dir C:\Users\Public\Desktop
Testfile1
Testfile2
Folder for the current user:
dir C:\Users\usera\Desktop
Testfile3
Testfile4
Now I want to get all files from Testfile1 till Testfile4 by looping trough C:\Users\usera\Desktop
Someone has a clue howto get a list of the files of both directories merged together?
Also not only for Desktop, there are other folders that behave the same way.
Pseudocode:
arrayDesktop = FunctionThatGetsAllFilesFrom(#"C:\Usera\Desktop");
foreach (var file in arrayDesktop)
{
Console.WriteLine(file);
}
this should now print out
Testfile1
Testfile2
Testfile3
Testfile4
They are separate folders on the file system. Windows just combines them both to display on the desktop. You are going to have to get all the files from both folders and combine them into a single list.
You can get the list of files in a given folder with Directory.GetFiles.
Once you have the files from both folders, you can combine them with the Linq Concat extension method.
This isn't tested code so forgive any errors, but it should be enough to get you started.
foreach (string dir in Directory.GetDirectories(#"c:\Users"))
{
string fullDir = Path.Combine(dir, "Desktop");
if (Directory.Exists(fullDir))
{
foreach (string file in Directory.GetFiles(fullDir))
{
Console.WriteLine(file);
}
}
}
Unless you're running this as an administrator though, you're likely to run into security issues i.e. unable to read the directory. In this instance, you're going to need the System.Net.NetworkCredential object and store the admin account in local cache - something like this.
NetworkCredential credential = new NetworkCredential(username, password, domain);
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(#"\\computer-uri"), "Basic", credential);
Use Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) and Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) to get the files on your Desktop and the Public one respectively.
For other Virtual Folders you can look at the documentation. But you still have to merge all the files yourself.
Related
Hello StackOverflow community,
I'm working for a C# web application that can show all necessary files in one folder. For example, you have a folder named "Maps" that stores all information about New York City. I will describe this folder here: The bolded word is folders.
Folder Maps:
->NewYorkCity
->>satellite.png
->>coordinates.txt
->>bridges.png
->>Road1
->>>satellite1.png
->>>roads.txt
->>>houses.png
As you can see, inside folder Maps we have folder NewYorkCity, and inside of this, we have folder Road1. Now I want to collect all files that have "*.png" type. It means I want to collect all images inside the root folder. The problem here is the algorithm to collect the file. I have thought to use "for loops" but I don't know the number of subfolders so I assumed it was impossible.
Here is the code to list the file with specified type that I have used but it works for files that in one folder and doesn't have any subfolders.
DirectoryInfo dInfo = new DirectoryInfo(zipPath); //Assuming Test is your Folder
FileInfo[] Files = dInfo.GetFiles("*.png"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
}
I hope you understand my question. Thank you.
You could start by reading the documentation, where you would find System.IO.DirectoryInfo.
Create a DirectoryInfo instance, and use, depending on what you want/need, any of its methods
EnumerateDirectories()
EnumerateFiles()
EnumerateFileSystemInfos()
Like so:
DirectoryInfo di = new DirectoryInfo(#"c:\Maps");
foreach (var fsi in di.EnumerateFileSystemInfos("*", SearchOptions.AllDirectories)
{
// Do something useful with fsi here
}
I have a quiz that has a login feature but, when you change pc you must also change the drive the file is located e.g D drive, E drive etc...
Currently its set to F. Is there something i can add that will make it automatically search each drive for the file?
Here is my code
if (File.Exists(#"F:\C# Completed quiz\adam new\Mario quiz\bin/PlayerDetails.txt"))
{
string[] lines = File.ReadAllLines(#"F:\C# Completed quiz\adam new\Mario quiz\bin/PlayerDetails.txt");
I'd recommend you just put it in the AppData or MyDocuments folder:
string filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "C# Completed quiz","adam new","Mario quiz","bin","PlayerDetails.txt");
//or Environment.SpecialFolder.MyDocuments
if (File.Exists(filename))
{
string[] lines = File.ReadAllLines(filename);
}
you need to enumerate the hard drives on the system and inspect them one at a time
https://msdn.microsoft.com/en-us/library/system.io.directory.getlogicaldrives(v=vs.110).aspx
shows how to enumerate the hard drives on the system
This answer uses what looks like a better way
How can I determine if a given drive letter is a local/mapped/usb drive?
Once you know a drive is a mounted drive the you should look at <drive>:/<your path>
Use Resource file to store your txt inside the application or just distribute it with your executable. To add resource file:
Right click on your project and select Properties
Go to Resources tab and create new file
Click Add resource -> Add Existing File...
Choose your text file and click Open
The file can now be accessed like string:
var lines = Properties.Resources.PlayerDetails;
If the file is in the same folder as your exe then you can access it in this way:
var lines = File.ReadAllLines("PlayerDetails.txt");
Edit: Note the comment below if you prefer to use this method.
This is really annoying problem and it's going to drive me mad. I like to read information such like files, directories ect. but my app cannot find anything OUTSIDE its folder it runs in.
I'm using Visual Studio 2015 and developing Windows Universal apps.
This routine under works very well if I change the directory inside the folder my app run like "Assets" and any other folder. But outside of my app folder result is zero, not even any errors :-(
Ok, Here is the simple code, What I Do Wrong?
private void GetThem_Click(object sender, RoutedEventArgs e)
{
string myDir = #"c:\mydir\";
string[] files;
files = Directory.GetFiles(myDir,"*.jpg");
foreach (string stuff in files)
{
RESULT.Text = RESULT.Text + stuff + " , ";
}
}
A quick search would have given you the answer : It is not possible to access the file system like a classic desktop app. The answer of #Rico Suter explain you what you can acces and how :
Directories which are declared in the manifest file (e.g. Documents, Pictures, Videos folder)
Directories and files which the user manually selected with the FileOpenPicker or FolderPicker
Files from the FutureAccessList or MostRecentlyUsedList
Files which are opened with a file extension association or via sharing
Once a file is picked by the user, you can add it to MostRecentlyUsedList or FutureAccessList to use it again later using this snippet (C#) from MSDN :
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Add to MRU with metadata (For example, a string that represents the date)
string mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "20120716");
// Add to FA without metadata
string faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
}
Then store the retrieved token because you will need it to access the file using GetFileAsync(token)
The program I am writing is a stock inventory system.
So the PC I wrote the program on can locate the files and folders to update on the PC as necessary as the path is valid.
string path = "C:\\Users\\ThisPC\\Documents\\Stock Documents\\Reciepts";
if (!Directory.Exists("C:\\Users\\ThisPC\\Documents\\Stock Documents\\Reciepts"))
{
Directory.CreateDirectory(path);
}
var fileName = #"c:\Users\ThisPC\Documents\Stock Documents\Tyre_File.xml";
This line is also used when I am updating quantities when an order is taken.
So obviously when I run this program in visual studio on another PC this path isn't recognized.
Is there a way that I can add a pointer to create and store my folder and documents in the My Documents on any pc the program loads in?
UPDATE-------------------------------------------------------
string path = "C:\\Users\\ThisPC\\Documents\\Stock Documents\\Customer Reciepts";
if (!Directory.Exists("C:\\Users\\ThisPC\\Documents\\Stock Documents\\Customer Reciepts"))
{
Directory.CreateDirectory(path);
}
This is the only one it wont work for, it creates a folder within a folder when the form is loaded, but your method doesnt work for that?
I believe that
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
is what you are looking for
You want the environment variable for MyDocuments, which will be unique for each user/computer.
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (Fubrowse.HasFile)
{
string path = Path.GetFullPath(Fubrowse.PostedFile.FileName);
//string root = Path.GetPathRoot(path);
GetFilesFromDirectory(path.Substring(0, path.LastIndexOf("\\")));
}
else
GeneralClass.ShowMessageBox("Please Select File First.");
}
private void GetFilesFromDirectory(string DirPath)
{
try
{
DirectoryInfo Dir = new DirectoryInfo(DirPath);
FileInfo[] FileList = Dir.GetFiles("*.cs", SearchOption.AllDirectories);
foreach (FileInfo FI in FileList)
Here, path is c:\windows\system32\inetsrv\config\. I want to get all sub directories's file name in FileList array.
The Windows account that's running your code needs read access to the folder (that typically requires admin rights).
If you're running the program from Visual Studio, that's your account. Run VS as administrator and your code should work should work.
If it's a web app, the app pool account needs read access to the folder.
If it's a windows service, the host account needs access.
I had the same issue. I couldn't get files from the C:\Windows\system32\intesrv\config because my system was 64 bit and my request redirect to C:\Windows\SysWOW64\system32\intesrv\config
More explanation is given by this answer.
PS. My answer is left here just for those who will be in search in future