最大的文件未显示

时间:2015-01-02 11:50:22

标签: c#

我正在做一个基于文件排序的编程任务。我遇到了解决最大文件的问题。我想让下面的代码做的是显示我系统中最大的文件。相反,它会通过我所有文件的完整列表。

以下是此特定部分的代码:

                for (int index = 0; index < files.Length; index++)
                {

                    fileSize = files[index].Length;

                    long largestSoFar = 0;

                    folderInfo = new DirectoryInfo("C:\\Windows");
                    files = folderInfo.GetFiles();

                    if (fileSize > largestSoFar)
                    {                            
                        string fileName = files[index].Name;
                        largestSoFar = files[index].Length;
                        long largestFile = largestSoFar;
                        Console.WriteLine("Largest file: {0}, {1} bytes", fileName, largestSoFar);
                        // It should be that only the largest file gets shown.
                    }
                }

2 个答案:

答案 0 :(得分:2)

请尝试以下代码

long largestSoFar = 0;
string largestFileName = string.Empty;
DirectoryInfo folderInfo = new DirectoryInfo("C:\\Windows");
FileInfo[] files = folderInfo.GetFiles();

for (int index = 0; index < files.Length; index++)
{

    long fileSize = files[index].Length;

    if (fileSize > largestSoFar)
    {
        largestFileName = files[index].Name;
        largestSoFar = files[index].Length;
    }
}

Console.WriteLine("Largest file: {0}, {1} bytes", largestFileName, largestSoFar);

答案 1 :(得分:1)

您在循环内部定义了largestSoFar,因此每次都会对其进行初始化,这就是您有效迭代所有文件的原因。它是循环的,它最终将包含最大的文件。循环结束后,您可以输出所有细节

        var fileName = "";
        long largestSoFar = 0;
        var folderInfo = new DirectoryInfo("C:\\Windows");
        var files = folderInfo.GetFiles();

        for (int index = 0; index < files.Length; index++)
            {

                long fileSize = (long) files[index].Length;
                if (fileSize > largestSoFar)
                {                            
                    fileName = files[index].Name;
                    largestSoFar = (long) files[index].Length;
                }
            }

            //write largest file information
            Console.WriteLine("Largest file: {0}, {1} bytes", fileName, largestSoFar);
            // It should be that only the largest file gets shown.