I want to get the full path of the file named wampmanager.conf on disk D. I coded the following for this:
private static string Scan(string path, string file)
{
try
{
foreach (var dir in Directory.EnumerateDirectories(path))
{
foreach (var fl in Directory.EnumerateFiles(dir, file))
{
if (!string.IsNullOrEmpty(fl))
{
return fl;
}
}
}
}
catch (Exception)
{
// ignored
}
return null;
}
var wmc = Scan(#"D:\", "wampmanager.conf");
MessageBox.Show(wmc);
It always returns null even though the wampmanager.conf file exists on the disk D. I guess it goes to a directory like d:\recovery\ that I don't have access to, then it crashes into a catch and returns null. But when I don't use try catch I always get access authorization error. How can I deal with this problem?
For each directory you must use SearchOption.AllDirectories to Includes the current directory and all its subdirectories in a search operation. Try this function:
private static string Scan(string path, string file)
{
foreach (var dir in Directory.EnumerateDirectories(path))
try
{
string[] files = Directory.GetFiles(dir, file, SearchOption.AllDirectories);
if (files.Length > 0)
{
return files[0];
}
}
catch (Exception e)
{
string s = e.Message;
}
return "not found!";
}
Related
Get Shared Folder System Path But Code
Return same Path Shared Folder Like '#\123.1.1.56\Pagal'
DirSearch("\\\\DESKTOP-2FFGFDM\\Packages");
static void DirSearch(string dir, string rootDir = null)
{
if (rootDir == null)
{
rootDir = dir;
}
try
{
foreach (string f in Directory.GetFiles(dir))
{
string filename = f.Substring(rootDir.Length);
Console.WriteLine(filename);
}
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(d);
DirSearch(d, rootDir);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I can Not Find Shared Folder System Path
So Pls. Help me.........
Thanks In Advance
To test if a network share exists you can use a DirectoryInfo
static void DirSearch(string dir, string rootDir = null)
{
if(!new DirectoryInfo(dir).Exists)
throw new Exception($"the provided directory {dir} is not valid.")
if (rootDir == null)
{
rootDir = dir;
}
try
{
foreach (string f in Directory.GetFiles(dir))
{
string filename = f.Substring(rootDir.Length);
Console.WriteLine(filename);
}
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(d);
DirSearch(d, rootDir);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
if this is a school assignment for recursive programming than that would work, however you can just get all files and directory without the recursion
foreach (string f in Directory.GetFiles(dir,"*.*",SearchOption.AllDirectories))
{
string filename = f.Substring(rootDir.Length);
Console.WriteLine(filename);
}
as these files come from directories you can get those out of the name
var dir="";
foreach (string f in Directory.GetFiles(dir,"*.*",SearchOption.AllDirectories))
{
string filename = f.Substring(rootDir.Length);
var directoryName = new FileInfo(filename).Directory.FullName;
if(directoryName!=dir)
{
Console.WriteLine(filename);
dir= directoryName ;
}
Console.WriteLine(filename);
}
We have a process from third-party vendor to drop sales and invetory data everyday and could have any of the following scenarios
Drop the right file. (Naming standard: test.xls)
Drop the right file but not follow the right naming standard. (Other
names could be test_mmddyyyy or testmmddyyyy)
No file dropped.
I am trying to build my logic around these scenarios and stuck at how to build my logic when the file exists but does not have the right naming standard and check for this condition and change the name of the file to the appropriate naming standard.
public void Main()
{
try
{
string filefullpathname = #"C:\Temp\test.xls";
if (File.Exists(filefullpathname) == false)
{
Console.WriteLine("File does not exist in the path");
}
// file exists but right naming standard not followed (Other names could be test_mmddyyyy or testmmddyyyy)
// how to check for this condition and change the name of the file to the naming standard
else
{
string dirname = #"C:\Temp\";
DirectoryInfo directory = new DirectoryInfo(dirname);
string filepartialname = "test";
FileInfo[] fileindirectory = directory.GetFiles(filepartialname + "*");
foreach (FileInfo filename in fileindirectory)
{
string fullname = filename.FullName;
bool ind = Path.HasExtension(fullname);
if (ind == false)
{
File.Move(fullname, directory + filepartialname + ".xls");
}
else
{
File.Move(fullname, directory + filepartialname + ".xls");
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception error)
{
Console.WriteLine(error);
}
}
It is not really clear as to if it is only the file name or a missing extension. So I put in both.
public void Main()
{
try
{
string dirname = #"C:\Temp\";
DirectoryInfo directory = new DirectoryInfo(dirname);
string filepartialname = "test";
FileInfo[] fileindirectory = directory.GetFiles(filepartialname + "*");
foreach (FileInfo filename in fileindirectory)
{
if (filename.Extension == "")
{
//doesn't have an extension
}
else if (!Regex.IsMatch(filename.Name.Replace(filename.Extension, ""), #"^[A-Z|a-z]$"))
{
//contains more then just test
}
else
{
//file is good
}
}
}
catch (Exception error)
{
Console.WriteLine(error);
}
}
Your explanation of what your inputs could be, and how you want to move those inputs isn't super clear, but this should get you started:
var expectedFilename = Path.Combine(someOtherDirectory, "test.xls");
// Matches test* and *.xls
var relevantFiles = Directory
.EnumerateFiles(searchDirectory, "*", SearchOption.TopDirectoryOnly)
.Where(f => Path.GetFileName(f).StartsWith("test") || Path.GetExtension(f).Equals(".xls"))
foreach (var file in relevantFiles)
{
// If there's more than one file matching the pattern, last one in wins
File.Move(file, expectedFilename);
}
Basically I am trying to make a program that empties or even deletes a certain file, the thing is, this file is about 3 or 4 or so folders past the macromedia folder, and it can be it different named folders for anyone, so that is why the string[] files is done like that, it just checks for basically "FlashGame.sol" in EVERY folder after the macromedia folder.
I commented where I need help, I basically need to empty the contents of the file, or just flat out delete it.
private void button1_Click(object sender, EventArgs e)
{
string path = textBox1.Text + "/AppData/Roaming/Macromedia"; //the person using the program has to type in the beginning of the directory, C:/Users/Mike for example
bool Exists = Directory.Exists(path);
try
{
if (Exists)
{
string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
string[] array = files;
for (int i = 0; i < array.Length; i++)
{
string info;
string text = array[i];
using (StreamReader streamReader = new StreamReader(text))
{
info = streamReader.ReadToEnd();
//erase the contents of the file here or even delete it
}
}
}
}
catch
{
MessageBox.Show("The given directory was not found", "Error", MessageBoxButtons.OK);
}
}
You can clear a file this way:
System.IO.File.WriteAllText(#"file.path",string.Empty);
So you should probably change your Code to:
string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
foreach (var file in files)
{
System.IO.File.WriteAllText(file, string.Empty);
}
Also take a look at Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), which gives the appdata directory of the current user.
Also never catching a Exception without handling it correctly. You already know, if the directory exists via your Exists Variable.
string path = Environment.ExpandEnvironmentVariables(#"%AppData%\Macromedia\"); // Example C:\Users\Mike\AppData\Roaming\Macromedia\
if (Directory.Exists(path)) {
string[] files = Directory.EnumerateFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
foreach (string file in files) {
try {
File.Delete(file);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
Program goes through directories and prints Avi files to textbox
public FileList()
{
InitializeComponent();
//Sets Drive Choices
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
driveChoice.Items.Add(d);
}
}
//Find Video Files
private void btnStart_Click(object sender, EventArgs e)
{
String path = driveChoice.Text;
if (path != "C:\\")
{
String[] allfiles = Directory.GetFiles(path, "*.avi*", System.IO.SearchOption.AllDirectories);
foreach (String file in allfiles)
{
tbFileList.Text = tbFileList.Text + file + "\r\n";
}
}
else
{
Application.Exit();
}
}
}
When ran I get an error.
Unauthorized Access 'I:\$RECYCLE.BIN\S-1-5-21-1332477098-3306142970-3529014387-1000\'
Can I set the program to just skip 'I:\$RECYCLE.BIN'
Looks like you need to switch to a recursive solution or some other loop rather than using 'AllDirectories'. That way you can provide some skip logic.
see this link http://support.microsoft.com/kb/303974
and this code snippet from that page:
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, txtFile.Text))
{
lstFilesFound.Items.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
In that code you would just check your sDir for the values you want to skip.
Now there is no way to have the AllDirectories option skip specific directories or ignore exceptions that occur from traversing. You will need to manually search the directory structure and deal with errors that occur
if !filePath.Contains("I:\$RECYCLE.BIN")
Use a lambda statement to exclude the system directories:
public FileList()
{
InitializeComponent();
//Sets Drive Choices
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
driveChoice.Items.Add(d);
}
}
//Find Video Files
private void btnStart_Click(object sender, EventArgs e)
{
String path = driveChoice.Text;
if (path != "C:\\")
{
DirectoryInfo root = new DirectoryInfo(path);
var rootFiles = root.GetFiles("*.avi");
var rootDirs = root.GetDirectories("*", SearchOption.TopDirectoryOnly).Where(d => !d.Name.Equals("System Volume Information") && !d.Name.Equals("$RECYCLE.BIN"));
foreach (var file in rootFiles)
{
tbFileList.Text = tbFileList.Text + file.FullName + "\r\n";
}
foreach (var dir in rootDirs)
{
foreach (var dirFile in dir.GetFiles("*.avi", SearchOption.AllDirectories))
{
tbFileList.Text = tbFileList.Text + dirFile.FullName + "\r\n";
}
}
}
else
{
Application.Exit();
}
}
I just tried the usage of the Lambda expression of excluding both folders from the returned string list in VS 2017. I observed something strange. If the lambda expression is directly added to the retrieval of the directories as in the string shown above the list still returns $RECYCLEBIN, however SVI folder is not returned. In order to make the lambda working correctly I needed to separate the 2 actions i.e:
var allDirs = rootDir.GetDirectories("*",SearchOption.TopDirectoryOnly);
var filteredDirs = allDirs.Where(d=> !d.Name.Equals("System Volume Information") && !d.Name.Equals("$RECYCLE.BIN"));
I am having a bit of trouble with this method.
When I loop through the FileInfo type objects in dragDropFiles and add each individually to the CLB I get the FullName property (full path to file, which is what I need) returned when the item is checked.
However with the hotFolderFiles instead of the path it gives me just the file name.
I do not understand this because they are adding the same object type in the same manner.
(I also tried getting the FileInfo for hot folder files using the DirectoryInfo instead of my Dictionary with same results)
Why is this behavior inconsistent?
(and how can I get it to return the fileInfo fullName instead of Name?)
public frmFilesFound(string hotFolderPath, Dictionary<string, FileInfo> dragDropFiles, Dictionary<string, FileInfo> hotFolderFiles, bool ReadOnly)
{
try
{
InitializeComponent();
readOnly = ReadOnly;
btnSelectAll.Visible = true;
clbSelectFilesFound.Visible = true;
clbSelectFilesFound.FormattingEnabled = true;
clbSelectFilesFound.Format += (s, e) => { e.Value = string.Format("{0}", ((FileInfo)e.ListItem).Name); };
foreach (FileInfo fileInfo in dragDropFiles.Values)
{
if (!clbSelectFilesFound.Items.Contains(fileInfo))
{
try
{
// If file not already present, add it to listbox
clbSelectFilesFound.Items.Add(fileInfo);
}
catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); }
}
}
//intended to be hot folder path
if (!String.IsNullOrEmpty(hotFolderPath))
{
DirectoryInfo dirInfo = new DirectoryInfo(hotFolderPath);
foreach (FileInfo fileInfo in dirInfo.GetFiles())
//foreach (FileInfo fileInfo in hotFolderFiles.Values)
{
if (!clbSelectFilesFound.Items.Contains(fileInfo))
{
try
{
clbSelectFilesFound.Items.Add(fileInfo);
}
catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); }
}
}
}
lblDisplayedSelectMessage.Text = "More than one file is waiting. Please select the files you would like to use.";
}
catch (Exception ex)
{ MessageBox.Show(ex.ToString()); }
}
That is because the DirectoryInfo.GetFiles method only fills in the name of the file, and not the full path.
Try this formatter if you only want to show the name of the file in all cases:
clbSelectFilesFound.Format += (s, e) => {
e.Value = Path.GetFileNameWithoutExtension(((FileInfo)e.ListItem).Name);
};
Why don't you just always Add(fileInfo.FullName) ?