C# Reading Paths From Text File Says Path Doesn't Exist [duplicate] - c#

This question already has answers here:
What's the fastest way to read a text file line-by-line?
(9 answers)
Closed 7 years ago.
I'm developing a small command line utility to remove files from a directory. The user has the option to specify a path at the command line or have the paths being read from a text file.
Here is a sample text input:
C:\Users\MrRobot\Desktop\Delete
C:\Users\MrRobot\Desktop\Erase
C:\Users\MrRobot\Desktop\Test
My Code:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Number of command line parameters = {0}", args.Length);
if(args[0] == "-tpath:"){
clearPath(args[1]);
}
else
if(args[0] == "-treadtxt:"){
readFromText(args[1]);
}
}
public static void clearPath(string path)
{
if(Directory.Exists(path)){
int directoryCount = Directory.GetDirectories(path).Length;
if(directoryCount > 0){
DirectoryInfo di = new DirectoryInfo(path);
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
else{
Console.WriteLine("No Subdirectories to Remove");
}
int fileCount = Directory.GetFiles(path).Length;
if(fileCount > 0){
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
}
else{
Console.WriteLine("No Files to Remove");
}
}
else{
Console.WriteLine("Path Doesn't Exist {0}", path);
}
}
public static void readFromText(string pathtotext)
{
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(pathtotext))
{
// Read the stream to a string, and write the string to the console.
string line = sr.ReadToEnd();
clearPath(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
}
My Problem:
When reading from the text file, it says that the first path doesn't exist, and prints all the paths to the prompt, despite that I have no Console.WriteLine(). However, if I plug these same paths and call -tPath: it will work. My issue seems to be in the readFromText() I just can't seem to figure it out.

This is the problem:
string line = sr.ReadToEnd();
That isn't reading a line of data - it's reading the whole file in one go. Your clearPath method expects its parameter to be a single path, not a bunch of lines glued together. The reason you're seeing all the paths is that clearPath is being called (with everything in one call), that "glued together" path isn't being found, and it's printing out the input in Console.WriteLine("Path Doesn't Exist {0}", path);.
I suspect you should use something like:
var lines = File.ReadAllLines(pathtotext);
foreach (var line in lines)
{
clearPath(pathtotext);
}

Related

Manually entering what to search for

I have a program that manually loops through files in a folder and searches for keywords, telling you which file has them.
class Program
{
static void Main()
{
string input = "";
Console.WriteLine("Where? ");
input = Console.ReadLine();
LoopedData(input);
Console.ReadLine();
}
static void LoopedData(string path)
{
string[] files;
string[] directories;
string lineToFind = keyword;
files = Directory.GetFiles(path);
foreach (string file in files)
{
int line = 1;
using (var reader = new StreamReader(file))
{
// read file line by line
string lineRead;
while ((lineRead = reader.ReadLine()) != null)
{
if ( lineRead.Contains(lineToFind))
{
Console.WriteLine("File {0}, line: {1}", file, lineRead);
Console.ReadLine();
}
else
{
Console.WriteLine(" ");
}
line++;
}
}
Console.WriteLine("Finished.....");
Console.ReadLine();
//Console.WriteLine(file);
// look for string here
}
directories = Directory.GetDirectories(path);
foreach (string directory in directories)
{
// Process each directory recursively
LoopedData(directory);
}
}
}
I have been able to manually enter which folders to search in but I am having difficulty in creating a similar way to do it for the keyword. I have tried referencing it in the Main class, with no success. I need a fresh pair of eyes.
Any search I try doesn't yield helpful results
It seems you already know what to do. Your doing it correctly for the path. To get the keyword from the user, just do the same thing as for the path:
static void Main()
{
string path = "";
string keyword = "";
Console.WriteLine("Where? "); // read path
path = Console.ReadLine();
Console.WriteLine("What? "); // read keyword
keyword = Console.ReadLine();
LoopedData(input, keyword);
Console.ReadLine();
}
And change your LoopedData's signature like that to pass the keyword as parameter:
static void LoopedData(string path, string keywork)
{
// your code
}

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

C# How to select specific subdirectory

im doing something similar to the cmd tree. And what im planning to check first C:\ than check the first folder in it if the first folder contains something in it go check it and so on until i get DirectoryNotFoundException. If i get such i want to skip the first folder and check the second one how to do that ?
static string path = #"C:\";
static void Main()
{
try
{
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] fileNames = di.GetDirectories();
}
catch (DirectoryNotFoundException)
{
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] fileNames = di.GetDirectories();
//i need to edit the picking of filenames.Something like PickSecond/Next
}
Console.ReadKey();
}
If you want to print the directory tree you can use recursion without getting any DirectoryNotFoundException. The following code will print to the console all the sub-directories starting from a specific path. The recursion works this way: every time a folder is found, if it's not empty then go to explore its sub-directories, otherwise go and check the next folder.
static void DirectoryTree(string directory, string indent = "")
{
try
{
DirectoryInfo currentDirectory = new DirectoryInfo(directory);
DirectoryInfo[] subDirectories = currentDirectory.GetDirectories();
// Print all the sub-directories in a recursive way.
for (int n = 0; n < subDirectories.Length; ++n)
{
// The last sub-directory is drawn differently.
if (n == subDirectories.Length - 1)
{
Console.WriteLine(indent + "└───" + subDirectories[n].Name);
DirectoryTree(subDirectories[n].FullName, indent + " ");
}
else
{
Console.WriteLine(indent + "├───" + subDirectories[n].Name);
DirectoryTree(subDirectories[n].FullName, indent + "│ ");
}
}
}
catch (Exception e)
{
// Here you could probably get an "Access Denied" exception,
// that's very likely if you are exploring the C:\ folder.
Console.WriteLine(e.Message);
}
}
static void Main()
{
// Consider exploring a more specific folder. If you just type "C:\"
// you are requesting to view all the folders in your computer.
var path = #"C:\SomeFolder" ;
Console.WriteLine(path);
if(Directory.Exists(path))
DirectoryTree(path);
else
Console.WriteLine("Invalid Directory");
Console.ReadKey();
}

This code taken from microsoft is only copying the text files in the main directory not sub-directories

Taken from: http://msdn.microsoft.com/en-us/library/dd383571.aspx
I've modified it to copy files, but even when I had it exactly as microsofts example, it still is ignoring the text file I placed in a subdirectory as a test...I'm dying to know what is going on here since I thought "SearchOption.AllDirectories" took care of that...
{
string sourceDirectory = #"C:\Users\root\Desktop\bms 2013\bms 2013";
string archiveDirectory = #"C:\Users\root\Desktop\test";
try
{
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt", SearchOption.AllDirectories);
foreach (string currentFile in txtFiles)
{
string fileName = currentFile.Substring(sourceDirectory.Length + 1);
File.Copy(currentFile, Path.Combine(archiveDirectory, fileName));
}
}
catch (Exception)
{
// Console.WriteLine(e.Message);
}
}

Categories