Error In search in Root Drive like D:\ - c#

I write this code and work when I select any folder (with search option = SearchOption.AllDirectories ) but for
Drive Like D:\ I get error
" access to path D:\System Volume Information is denied"
and I add "\" to this path but still get error
if (dirListBox.Items.Count == 0)
{
foreach (int Index in disksListBox.CheckedIndices)
{
String Dir = disksListBox.Items[Index].ToString().Substring(0, 2);
Dir += #"\";
if (CheckExists(Dir))
{
Dirs.Add(Dir);
}
}
}
else
{
for (int Index = 0; Index < dirListBox.Items.Count; Index++)
{
String Dir = dirListBox.Items[Index].ToString();
Dirs.Add(Dir);
}
}
if (rdb_thisdir.Checked == true)
OptionDir = SearchOption.TopDirectoryOnly;
else
OptionDir = SearchOption.AllDirectories; // when search D:\ , Get Error But Work for Folder
if (rdbversion1.Checked == true)
{
ListViewItem lstitm = new ListViewItem();
foreach (String Dir in Dirs)
{
try
{
DirectoryInfo DirInfo = new DirectoryInfo(Dir);
FileInfo[] FileS = DirInfo.GetFiles(SearchPattern,OptionDir); //error when Dir="D:\\"
foreach (FileInfo file in FileS)
{
try
{
if (Check_Attributes(file) && Check_DateTime(file))
{
listFileFounded.Items.Add(file.FullName.ToString());
lstitm = lwfound.Items.Add(file.Extension.ToString());
lstitm.SubItems.Add(file.Name.ToString());
lstitm.SubItems.Add((file.Length / 1024).ToString());
lstitm.SubItems.Add(file.Attributes.ToString());
lstitm.SubItems.Add(file.FullName.ToString());
}
}
catch
{ }
}
}
catch ()
{
}
}

Your D: drive contains a folder "System Volume Information" that you don't have the privileges to access. So you will need to either not access it, or catch the exception and handle it to your liking. Not having access to a folder is not uncommon outside of ones own PC, so you might want to think about handling that scenario in your user interface. Maybe paint the folder in grey or display a lock icon or something.

There was a trick to do it. Do Enable Sharing to this folder.
For more information id here
Or do this trick .....
static void RecursiveGetFiles(string path)
{
DirectoryInfo dir = new DirectoryInfo(path);
try
{
foreach (FileInfo file in dir.GetFiles())
{
MessageBox.Show(file.FullName);
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to folder: " + path);
}
foreach (DirectoryInfo lowerDir in dir.GetDirectories())
{
try
{
RecursiveGetFiles(lowerDir.FullName);
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Access denied to folder: " + path);
}
}
}
}
kamil Krasinsky answered it .. here

Related

Access to the directory denied in C# - Console Application

I am trying to access the Documents directory and sub-directories, but every time it says access denied. I see the Exception:
System.UnauthorizedAccessException: Access to the path 'C:\Users\MyUser\Documents\My Music' is denied
Here is my code - all I am trying to do is get the total size of this directory.
class Program
{
static void Main(string[] args)
{
try {
// Make a reference to a directory.
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
DirectoryInfo di = new DirectoryInfo(path);
// Get a reference to each file in that directory.
FileInfo[] fiArr = di.GetFiles(".", SearchOption.AllDirectories);
// Display the names and sizes of the files.
Console.WriteLine("The directory {0} contains the following files:", di.Name);
long size = 0;
foreach (FileInfo f in fiArr)
{
size += f.Length;
size++;
}
Console.WriteLine("The size of desktop files." + size);
}
catch(Exception e)
{
Console.WriteLine("Exceptions {0}" , e);
}
}
}
From what I can gather from skimming this thread it could be that these folders are soft links provided for Windows backward compatibility.
For resolving the coding problem, you could make your own recursive folder search that ignores the exceptions thrown when the current user does not have access to a given folder.
Something like this perhaps:
static IEnumerable<FileInfo> GetAllFilesRecursive(string path)
{
var di = new DirectoryInfo(path);
var files = new List<FileInfo>();
files.AddRange(di.GetFiles("."));
foreach (var directory in Directory.GetDirectories(path))
{
try
{
files.AddRange(GetAllFilesRecursive(directory));
}
catch (UnauthorizedAccessException) // ignore directories which the user does not have access to
{}
}
return files;
}
Then rewrite your code to use the new function:
static void Main(string[] args)
{
try
{
// Make a reference to a directory.
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fiArr = GetAllFilesRecursive(path);
// Display the names and sizes of the files.
Console.WriteLine("The directory {0} contains the following files:", path);
long size = 0;
foreach (FileInfo f in fiArr)
{
size += f.Length;
size++;
}
Console.WriteLine("The size of desktop files." + size);
}
catch (Exception e)
{
Console.WriteLine("Exceptions {0}", e);
}
}
The search should be on TopDirectoryOnly and not on AllDirectories.
The problem is in this line:
FileInfo[] fiArr = di.GetFiles(".", SearchOption.AllDirectories);
Change it to:
FileInfo[] fiArr = di.GetFiles(".", SearchOption.TopDirectoryOnly);
This should work.
Some SpecialFolders needs specific Admin priviledges to run without any exception. You must run your code in Admin priviledges.

Proceed If File Doesn't Exist

I have the following code:
public static void readtext(string pathtoText)
{
if (File.Exists(pathtoText))
{
string[] lines = System.IO.File.ReadAllLines(pathtoText);
// Display the file contents by using a foreach loop.
foreach (string line in lines)
{
clearPath(line);
}
}
else
{
Console.WriteLine("{0} doesn't exist, or isn't a valid text file", pathtoText);
}
}
public static void clearPath(string path)
{
if(Directory.Exists(path))
{
int directoryCount = Directory.GetDirectories(path).Length;
if(directoryCount > 0)
{
Console.WriteLine("{0} has Subdirectories to Remove", path);
DirectoryInfo di = new DirectoryInfo(path);
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
else
{
Console.WriteLine("{0} has no directories to remove", path);
}
int fileCount = Directory.GetFiles(path).Length;
if (fileCount > 0)
{
Console.WriteLine("{0} has files to Remove", path);
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch(System.IO.IOException)
{
Console.WriteLine("Please Close the following File {0}", file.Name);
}
}
}
}
else
{
Console.WriteLine("Path Doesn't Exist {0}", path);
}
}
My function reads directories from a text file and passes it to clearPath which checks if the directory exists, and if so, cleans it. My problem is that, if a directory doesn't exist, it stops the program(it doesn't move to the next directory to check if it exists and clean, the for each loop just stops) .
How do I get it to the next directory even if specific directory doesn't exist?
it is possible that you have empty lines in your file?
you can try something like that:
foreach (string line in lines)
{
if (!String.IsNullOrWhiteSpace(line))
{
clearPath(line.trim());
}
}

Deleting a specific folder and it's files ASP.NET

Alright so I'm having a bit of an issue here. I'm trying to delete a specific folder inside another folder on my webserver using ASP.NET (C#) The folder being deleted is based on a textbox.
The directory is like this
/images/folderx
folderx = txtDelFolder.Text;
The problem is that everything I try deletes every single thing inside the images folder. I'm guessing that it is not recognizing my folder in the filepath
string path = #"\httpdocs\images\ +
txtDelFolder.Text;
I have also tried
string path = #"\httpdocs\images\ +
txtDelFolder.Text + "\";
Tried all this with both single '\' and double '\'
Would appreciate any help on this
Also where it says <directfilepath> I actually have the filepath typed out, just didn't want to share that here.
****edit****
string path = Server.MapPath("~/imagestest/" + txtEditTitle.Text);
if(Directory.Exists(path))
{
DeleteDirectory(path);
}
}
}
private void DeleteDirectory(string path)
{
foreach(string filename in Directory.GetFiles(path))
{
File.Delete(filename);
}
foreach(string subfolders in Directory.GetDirectories(path))
{
Directory.Delete(subfolders, true);
}
}
Try this:
private void DeleteFiles(string folder)
{
string path=Server.MapPath("~/httpdocs/images/" + folder);
string[] files=Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
File.Delete(file);
}
//then delete folder
Directory.Delete(path);
}
try this one :
public void DeleteFolder(string folderPath)
{
if (!Directory.Exists(folderPath))
return;
// get the directory with the specific name
DirectoryInfo dir = new DirectoryInfo(folderPath);
try
{
foreach (FileInfo fi in dir.GetFiles())
fi.Delete();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Don't see why this wouldn't work:
public static bool DeleteDirectory(string input)
{
if (Directory.Exists(input))
{
Directory.Delete(input, true);
return !Directory.Exists(input);
}
else
return true;
}
string thePath = Server.MapPath(#"~/images/");
thePath = Path.Combine(Path.GetFullPath(thePath), txtInput.Text);
if(DeleteDirectory(thePath))
Console.WriteLine("YAY");
else
Console.WriteLine("BOO");

Delete all files from a directory except for folder and it's contents

I am trying to remove all files on my storage card without removing one. I can keep the directory I specify but not its contents with my current code. It just leaves the blank
folder data because it removes everything inside. How can I keep it from removing that folder and its contents?
private void button1_Click(object sender, EventArgs e)
{
ScanDirectory scanDirectory = new ScanDirectory();
scanDirectory.WalkDirectory(#"/Storage Card");
scanDirectory.WalkDirectory(#"/Application");
}
public class ScanDirectory
{
public void WalkDirectory(string directory)
{
WalkDirectory(new DirectoryInfo(directory));
}
private static void WalkDirectory(DirectoryInfo directory)
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}
The problem is the way in which the recursive function calls are done: the main function private static void WalkDirectory(DirectoryInfo directory) deletes all files and is called every time (even while analysing a subdirectory). Here you have a fix to make this code work as you wish:
private static void WalkDirectory(DirectoryInfo directory)
{
if (directory.Name.ToLower() != "data")
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}
private static void WalkDirectory(DirectoryInfo directory)
{
if (directory.Name.ToLower() != "data")
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}

Error while handling multiple txt files

I'm constructing a program to search all .xml inside a folder setted by user (Source folder) and copy all these files to another folder (Destination folder).
My program is able to search all XML within all sub folders from (Source folder), the result returns around 5000 files that are placed on a list, this list is worked later by a function, but he can only work with 31 files, then appears "not responding "and the debugger shows that the program is staying a long time in the execution.
Here is my code:
Button action:
private void btnCopiarSalvar_Click(object sender, EventArgs e)
{
foreach (string name in listFileNames)
{
if (readXML(name ))
{
tbArquivo.Text = name ; //Feedback textbox, tell the current filename
}
}
pbStatus.Increment(50);
cbFinal.Checked = true; //Feedback checkBox, to tell user that the task is over.
}
Function ReadXML
public bool readXML(string name)
{
//foreach (string nome in listaArquivos)
//{ //I tried to the foreach inside, but nothing Works.
try
{
string text = null;
string readBuffer = File.ReadAllText(name);
text = readBuffer.Aggregate(text, (current, b) => current + b);
var encoding = new ASCIIEncoding();
Byte[] textobytes = encoding.GetBytes(text);
if (!File.Exists(destino))
{
string destinoComNomeArquivo = destino + "\\" + Path.GetFileName(nome);
using (FileStream fs = File.Create(destinoComNomeArquivo))
{
foreach (byte textobyte in textobytes)
{
fs.WriteByte(textobyte);
pbProcess.PerformStep();
}
Console.WriteLine("Arquivo gravado " + Path.GetFileName(nome));
}
}
pbProcess.PerformStep();
}
catch (Exception e)
{
Console.WriteLine(e);
}
//}
return true;
}
Error: ContextSwitchDeadlock was detected.
Tried Solution: Disable Managed Debug Assistants.
After disabling the MDA, the programs still only read-copy 31 files (of 5k).
The first thing i recommand is ... don't do that kind of file copy! use the File.Copy function instead.
Try to use this code snipping from MSDN:
void DoCopy(string path)
{
var copytask = new Task(() =>
{
string destinoComNomeArquivo = #"C:\" + Path.GetFileName(path);
DirectoryCopy(path, destinoComNomeArquivo, false);
});
copytask.Start();
}
private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
var counter = 0;
var maxcounter = files.Count();
while (maxcounter < counter)
{
var item = files.ElementAt(counter).Name;
WriteAsnc(item);
counter++;
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
const int _maxwritingprocess = Environment.ProcessorCount;
int _currentwritingtasks;
void WriteAsnc(string filepath)
{
_currentwritingtasks++;
var task = Task.Factory.StartNew(() =>
{
XDocument doc = XDocument.Load(filepath);
doc.Elements().First().Add(new XAttribute("Attribute Name","Attribute Value"));
doc.Save(filepath);
_currentwritingtasks--;
});
if(_currentwritingtasks == _maxwritingprocess)
task.Wait();
_currentwritingtasks--;
}
The next point the ContextSwitchDeadlock is a Threading problem and i thing your pbProcess is the source. What does that Process do i don't see anything of that process and i don't thing it is Impotent for your copy

Categories