【发布时间】:2016-01-05 20:17:17
【问题描述】:
我正在开发一个小型命令行实用程序来从目录中删除文件。用户可以选择在命令行指定路径或从文本文件中读取路径。
这是一个示例文本输入:
C:\Users\MrRobot\Desktop\Delete
C:\Users\MrRobot\Desktop\Erase
C:\Users\MrRobot\Desktop\Test
我的代码:
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);
}
}
}
}
我的问题:
从文本文件中读取时,它说第一个路径不存在,并打印提示的所有路径,尽管我没有Console.WriteLine()。但是,如果我插入这些相同的路径并调用 -tPath: 它将起作用。我的问题似乎在readFromText() 我似乎无法弄清楚。
【问题讨论】:
-
除此之外,我强烈建议您开始遵循 .NET 命名约定。
标签: c# command-line text-files streamreader