command line - C# Reading Paths From Text File Says Path Doesn't Exist -
this question has answer here:
i'm developing small command line utility remove files directory. user has option specify path @ command line or have paths being read text file.
here 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 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 remove"); } } else{ console.writeline("path doesn't exist {0}", path); } } public static void readfromtext(string pathtotext) { try { // open text file using stream reader. using (streamreader sr = new streamreader(pathtotext)) { // read stream string, , write string console. string line = sr.readtoend(); clearpath(line); } } catch (exception e) { console.writeline("the file not read:"); console.writeline(e.message); } } } } my problem:
when reading text file, says first path doesn't exist, , prints paths prompt, despite have no console.writeline(). however, if plug these same paths , call -tpath: work. issue seems in readfromtext() can't seem figure out.
this problem:
string line = sr.readtoend(); that isn't reading line of data - it's reading whole file in 1 go. clearpath method expects parameter single path, not bunch of lines glued together. reason you're seeing paths clearpath being called (with in 1 call), "glued together" path isn't being found, , it's printing out input in console.writeline("path doesn't exist {0}", path);.
i suspect should use like:
var lines = file.readalllines(pathtotext); foreach (var line in lines) { clearpath(pathtotext); }
Comments
Post a Comment