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
Related
I want to get all files and folders in Drive C.
In fact, I want a list of all the files on the drive. All the files along with their path.
I use this code .but encounters an error.
static void Main(string[] args)
{
System.IO.DriveInfo di = new System.IO.DriveInfo(#"C:\");
System.IO.DirectoryInfo dirInfo = di.RootDirectory;
System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");
System.IO.DirectoryInfo[] dirInfos = dirInfo.GetDirectories("*.*");
foreach (System.IO.DirectoryInfo d in dirInfos)
{
string[] filePaths = Directory.GetFiles(d.FullName, "*.*",
SearchOption.AllDirectories);
}
}
You can simply exclude directories that you can't access by searching them one by one and surrounding all of the searches with a try-catch block. Here is an example:
Console.WriteLine("Input search pattern (or empty to search all):");
string pattern = Console.ReadLine();
if (pattern == "")
{
pattern = "*";
}
List<string> allDirectories = new List<string>{ #"C:\" });
Stack<string> directories = new Stack<string>(allDirectories);
List<string[]> allFiles = new List<string[]>();
while (directories.Count > 0)
{
try
{
Console.WriteLine("Searching " + directories.Peek() + " for " + pattern);
foreach (string dir in Directory.GetDirectories(directories.Pop()))
{
directories.Push(dir);
allDirectories.Add(dir);
try
{
allFiles.Add(Directory.GetFiles(dir, pattern, SearchOption.TopDirectoryOnly));
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
}
}
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
}
}
Console.WriteLine("FINISHED");
This will collect all files into the allFiles list (as paths) and directories into the allDirectories list.
This runs for ~10 minutes for me, so don't debug to many times.
First thing you need to do is compiling your C# app with a manifest file that asks for root privileges (follow instructions from: How do I force my .NET application to run as administrator?).
Next, What you should do is achieve any kind of a user/running-app with admin permissions and let it start your C# app.
I think that if you'll do the above via an app with root privileges then no UAC will pop-up to the user when the C# app will start.
If your app don't have root permission you won't be able to read the directory tree of unauthorized folders.
C# is a managed language, which means C# counts on the operating system to run and for that reason it can't bypass the operating system. Even with root permission, the operating system will be aware of your app actions.
BUT if your target is to figure out if a C# dll can maliciously read the folder tree of C drive, I think it's possible:
You need to compile your C# code into a exe file with a manifest as I've described above.
Then, create a batch file that will start a CLR process with root privileges (it'll probably alert the user with a UAC prompt but a common user won't suspect the CLR).
Make sure your batch will run with the user privileges and not the default ones or the next step won't work.
Your batch should tell the clr to load C# exe and I believe either no UAC will be prompted or either the batch could accept on behalves of the user without any prompt.
4'. If I'm wrong, perhaps the article https://www.codeproject.com/Articles/607352/Injecting-NET-Assemblies-Into-Unmanaged-Processes#PuttingItAllTogether will help you inject the exe into the clr without a UAC prompt.
Let me know if you continued the research by my suggestion and what was the results :-)
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)
Greeting.
I'm developing a ASP.NET Web Application and is trying to list the files in multiple layer of folders on the same server, but is on different folder (The files folder and Web Application folder).
The reason why I would like to access to the file is because I would required to read the creation date and the file name of the file. My application populate the details on gridview dynamically without any use of database and also provide the functions for downloading it one-by-one or zip all files together and download it as a compressed zip file.
Currently my approach is to share that folders out and my application is accessing it as if like a file system. To make it worse, I'm not allowed to host another IIS Web App.
Question:-
Is there any other workaround other than accessing it as a shared folder?
Updated
private List<FileData> getFilesList(DateTime? startDate, DateTime? endDate, string exDir)
{
DirectoryInfo dir = new DirectoryInfo(exDir);
List<FileData> fileDataList = new List<FileData>();
FileData fileEnt = null;
if (!dir.Exists)
{
return null;
}
if (startDate == null && endDate == null)
{
foreach (FileInfo fileInfo in dir.GetFiles())
{
fileEnt = new FileData();
fileEnt.fileName = fileInfo.Name;
fileEnt.createdDate = fileInfo.CreationTime;
fileEnt.stationCode = fileInfo.Name.Substring(0, 4);
fileEnt.filePath = fileInfo.DirectoryName;
fileDataList.Add(fileEnt);
}
}
else
{
foreach (FileInfo fileInfo in dir.GetFiles())
{
if (fileInfo.CreationTime > startDate && fileInfo.CreationTime < endDate)
{
fileEnt = new FileData();
fileEnt.fileName = fileInfo.Name;
fileEnt.createdDate = fileInfo.CreationTime;
fileEnt.stationCode = fileInfo.Name.Substring(0, 4);
fileEnt.filePath = fileInfo.DirectoryName;
fileDataList.Add(fileEnt);
}
}
}
return fileDataList;
}
This is a snippet of partially what is from my ASP.NET Web Application.
I'm trying to access it as in C:\FolderA\SubfolderB as I have created a page of configuration ASP.NET page to mimic folder browsing modal to allowed my user to specify which folder should my web application to list out all the files inside.
The flow goes like :-
1) User select a parent folder (Folder A)
2) System get list of subfolders from Folder A.
3) System iterate through all the subfolders to list all the subfolder's file name and information from the list of subfolders.
However, whenever I specify "F:\Reports\FolderA\" I'm unable to get the full listing. However, when I use \ServerName\FolderA, I can get the full list.
My application is located in E:\NETPrograms while my files are located in F:\Reports\FolderA.
Now, security team says that sharing folder is prohibited and I'm required to find another workaround for it.
Please advice.
i suppose you have given it permission by Sharing that folder with Everyone.
If you don't want to share it publicly, you can go to Folder Property -> Security and give Read permissions to IIS_USER.
This way it can be accessed by IIS_USER and used in your application and will not shared publicly.
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.
I'm getting a Unauthorized Access Exception
in a file which I can delete manually.
in a folder where I'm able to delete by code other files
and the file isn't marked as read only
besides, I'm using Windows XP in a standalone PC and I have not assigned any permissions to the folder or the file.
no other process is using the file
If it helps, this is the code where the exception ocurrs:
protected void DeleteImage(string imageName)
{
if (imageName != null)
{
string f = String.Format("~/Images/{0}", imageName);
f = System.Web.Hosting.HostingEnvironment.MapPath(f);
if (File.Exists(f))
{
if (f != null) File.Delete(f);
}
}
}
Why could this happen?
I encountered the same problem, and found that writing my own Directory.Delete wrapper fixed it up. This is recursive by default:
using System.IO;
public void DeleteDirectory(string targetDir)
{
File.SetAttributes(targetDir, FileAttributes.Normal);
string[] files = Directory.GetFiles(targetDir);
string[] dirs = Directory.GetDirectories(targetDir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(targetDir, false);
}
If the directory contains a read only file, it won't delete that using Directory.Delete. It's a silly implementation by MS.
I am surprised no one suggested this method on the internet, which deletes the directory without recursing through it and changing every file's attributes. Here's that:
Process.Start("cmd.exe", "/c " + #"rmdir /s/q C:\Test\TestDirectoryContainingReadOnlyFiles");
(Change a bit to not to fire a cmd window momentarily, which is available all over the internet)
If it's not read-only it's possible that it is currently in use by another process.
Checking the obvious first...
When you open the file property and take a look at its security settings. Does the user running the code (i.e. if this is ASP.NET, Network Services / Domain Service Account) has access to actually delete the file?
If it is not, then change it and try again.
Are you running as administrator when trying to delete this manually?
If you are, then that's probably why you are able to delete it manually. Try deleting it as the account running your ASP.NET (I'm assuming it is ASP.NET since you are using System.Web.Hosting.HostingEnvironment.MapPath.)
If both failed, try to see if any other process is actually currently using this file. Good tool to find out is SysInternal Process Monitor. Filter it by path containing your filename and you should see if anything is using it. Terminate the process and try again.
I too faced the Same Problem but eventually came up with a Generic Approach. Below are my codes.
String pathfile = "C:\Users\Public\Documents\Filepath.txt" ;
if (!Directory.Exists(pathfile))
{
File.SetAttributes(pathfile, FileAttributes.Normal);
File.Delete(pathfile);
}
using (FileStream fs = File.Create(pathfile))
{
Byte[] info = new UTF8Encoding(true).GetBytes("What Ever Your Text is");
fs.Write(info, 0, info.Length);
File.SetAttributes(pathfile, FileAttributes.ReadOnly);
}
You, the human user, have a login with certain rights. The Web server might have a different login with different rights. A user starting with IUSR_XXXX or some such thing. Make sure that user has rights to the directory.
Without more info on the context in which you are deleting the file, I assume that the Web server user has different rights to a file than you do.