处理转换为字符串时处理Convert.ToBase64String内存不足异常

时间:2018-07-22 10:44:43

标签: c#

当我尝试对.zip文件夹执行以下操作时,女巫中包含一些视频,我的记忆不足。

Byte[] bytes = File.ReadAllBytes(@"C:\folderWithVideos.zip");  
String base64File= Convert.ToBase64String(bytes);//<----- out of memory exception

如何正确处理此异常?我的意思是没有try-catch,我已经尝试过类似的事情:

String base64File;
if (bytes.Length <= System.Int32.MaxValue)
   base64File = Convert.ToBase64String(bytes);

但这没有帮助,但是bytes.Length <= 255确实有帮助,但是我不确定255是正确的数字。

1 个答案:

答案 0 :(得分:0)

根据the blog中显示的代码,以下代码有效。

// using  System.Security.Cryptography
private void ConvertLargeFile()
{
    //encode 
    var filein = @"C:\Users\test\Desktop\my.zip";
    var fileout = @"C:\Users\test\Desktop\Base64Zip";
    using (FileStream fs = File.Open(fileout, FileMode.Create))
    using (var cs = new CryptoStream(fs, new ToBase64Transform(),
                                                CryptoStreamMode.Write))

    using (var fi = File.Open(filein, FileMode.Open))
    {
        fi.CopyTo(cs);
    }
    // the zip file is now stored in base64zip    
    // and decode
    using (FileStream f64 = File.Open(fileout, FileMode.Open))
    using (var cs = new CryptoStream(f64, new FromBase64Transform(),
                                                CryptoStreamMode.Read))
    using (var fo = File.Open(filein + ".orig", FileMode.Create))
    {
        cs.CopyTo(fo);
    }
    // the original file is in my.zip.orig
    // use the commandlinetool 
    //  fc my.zip my.zip.orig 
    // to verify that the start file and the encoded and decoded file 
    // are the same
}

代码使用System.Security.Cryptography命名空间中的标准类,并使用CryptoStreamFromBase64Transform及其对应的ToBase64Transform