2010-03-06 57 views
1

我一直在研究模块练习,并且遇到了读取文本文件并打印其详细信息的代码片段。如何在代码中给出文件路径而不是命令行

它工作正常,但我只想知道如何给代码本身的文本文件的路径,而不是在命令行中给出路径。

以下是我的代码。

class Module06 
{ 
    public static void Exercise01(string[] args) 
    { 
     string fileName = args[0]; 
     FileStream stream = new FileStream(fileName, FileMode.Open); 
     StreamReader reader = new StreamReader(stream); 
     int size = (int)stream.Length; 
     char[] contents = new char[size]; 
     for (int i = 0; i < size; i++) 
     { 
      contents[i] = (char)reader.Read(); 
     } 
     reader.Close(); 
     Summarize(contents); 
    } 

    static void Summarize(char[] contents) 
    { 
     int vowels = 0, consonants = 0, lines = 0; 
     foreach (char current in contents) 
     { 
      if (Char.IsLetter(current)) 
      { 
       if ("AEIOUaeiou".IndexOf(current) != -1) 
       { 
        vowels++; 
       } 
       else 
       { 
        consonants++; 
       } 
      } 
      else if (current == '\n') 
      { 
       lines++; 
      } 
     } 
     Console.WriteLine("Total no of characters: {0}", contents.Length); 
     Console.WriteLine("Total no of vowels : {0}", vowels); 
     Console.WriteLine("Total no of consonants: {0}", consonants); 
     Console.WriteLine("Total no of lines  : {0}", lines); 
    } 
} 
+0

此代码不能有效地使用.NET框架。好吧,我猜想一本语言书。但一定要获得另一本专注于框架的书。这是你必须学习的另外90%。 – 2010-03-06 10:54:46

回答

1

阅读的文本文件的是File.ReadAllText容易得多,那么你就不需要考虑关闭你只需要使用它的文件。它接受文件名作为参数。

string fileContent = File.ReadAllText("path to my file"); 
0
string fileName = @"path\to\file.txt"; 
2

在你static void Main,叫

string[] args = {"filename.txt"}; 
Module06.Exercise01(args); 
相关问题