C# The file is too long. This operation is currently limited to supporting files less than 2 gigabytes in size.

FredGrit發表於2024-11-16
namespace ConsoleApp4
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string bigFile = @"C:\Users\fred\Downloads\ebook-master.zip";
            ReadBigFile(bigFile);            
        }

        static void ReadBigFile(string filePath)
        {
            try
            {
                var bytes = File.ReadAllBytes(filePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}

The solution is use FileStream

static void Main(string[] args)
{
    string bigFile = @"C:\Users\fred\Downloads\ebook-master.zip";
    ReadBigFileViaFileStream(bigFile);            
}

static void ReadBigFileViaFileStream(string filePath)
{
    try
    {
        using(FileStream fs=new FileStream(filePath,FileMode.Open,FileAccess.Read))
        {
            Console.WriteLine(fs.Length.ToString("N3"));               
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        Console.WriteLine(ex.StackTrace);
    }
}

相關文章