繁体   English   中英

如何在代码而不是命令行中提供文件路径

[英]How to give a file path in code instead of command line

我一直在进行模块练习,遇到了这段代码片段,该片段读取文本文件并打印有关该文件的详细信息。

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

下面是我的代码。

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

在您的static void Main ,调用

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

使用File.ReadAllText读取文本文件要容易得多,因此您不必考虑关闭仅使用它的文件。 它接受文件名作为参数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM