3

尝试从列表中获取文件大小,然后将结果输出到文本文件。目前,我已经能够从文件中读取前半部分工作,检查文件是否存在,然后输出到控制台和文本文件

我是新编程“本周刚开始”。这可能是任何简单的问题并尝试过,但不能完全正常工作

我已经尝试将它放在 foreach 循环中并尝试读取路径,但它不起作用。

        DirectoryInfo di = new DirectoryInfo(path);
        FileInfo[] fiArr = di.GetFiles();
        foreach (FileInfo f in fiArr)

到目前为止我的代码

    static void Main(string[] args)
    {

        string[] lines = System.IO.File.ReadAllLines(@"C:\Locations2.txt");
        foreach (string path in lines)
            if (File.Exists(path))
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Results.txt", true))
                {
                    file.WriteLine("File found" + "\t" + path);
                    Console.WriteLine("File found" + "\t" + path);
                }


            else
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Results.txt", true))
                {
                    file.WriteLine("Does not Exist" + "\t" + path);
                    Console.WriteLine("Does not Exist" + "\t" + path);
                }

    }

提前谢谢你,如果代码很糟糕,你能告诉我为什么不应该这样做吗?

4

1 回答 1

9

FileInfo您可以通过类获取有关文件的信息(包括其大小)

例如

var fileName = @"C:\Locations2.txt";
FileInfo fi = new FileInfo(fileName);
var size = fi.Length;
Console.WriteLine("File Size in Bytes: {0}", size);

您放在循环中的上面的代码是正确的概念,只是错误的实现。如果您知道要打开的文件名,则无需经过DirectoryInfo.GetFiles路由。直接访问就行了FileInfo

所以你的代码看起来像这样:

static void Main(string[] args)
{

    string[] lines = System.IO.File.ReadAllLines(@"C:\Locations2.txt");
    foreach (string path in lines)
        if (File.Exists(path))
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Results.txt", true))
            {
                file.WriteLine("File found" + "\t" + path);
                Console.WriteLine("File found" + "\t" + path);

                FileInfo fi = new FileInfo(path);
                var size = fi.Length;
                file.WriteLine("File Size in Bytes: {0}", size);
                Console.WriteLine("File Size in Bytes: {0}", size);
            }


        else
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Results.txt", true))
            {
                file.WriteLine("Does not Exist" + "\t" + path);
                Console.WriteLine("Does not Exist" + "\t" + path);
            }

}
于 2013-02-23T02:19:54.730 回答