我对从 long 到 int 的转换的安全性有疑问。我担心我写的方法可能会在这次转换中失败。你能看看下面的代码并告诉我是否可以编写一些可以避免可能失败的代码吗?
提前谢谢你。
public static string ReadDecrypted(string fileFullPath)
{
string result = string.Empty;
using (FileStream fs = new FileStream(fileFullPath, FileMode.Open, FileAccess.Read))
{
int fsLength = (int)fs.Length;
byte[] decrypted;
byte[] read = new byte[fsLength];
if (fs.CanRead)
{
fs.Read(read, 0, fsLength);
decrypted = ProtectedData.Unprotect(read, CreateEntropy(), DataProtectionScope.CurrentUser);
result = Utils.AppDefaultEncoding.GetString(decrypted, 0, decrypted.Length);
}
}
return result;
}
最佳答案
简短的回答是:是的,这样您将无法处理任何长度 >= 2 GB 的文件!
如果您不希望有任何大文件,那么您可以直接在 using block 的开头插入:
if (((int)fs.Length) != fs.Length) throw new Exception ("too big");
否则你不应该转换为 int,而是改变 byte[] read = new byte[fsLength];
到 byte[] read = new byte[fs.Length];
并使用循环读取最大“ block ”中的文件内容。每个 block 2 GB。
另一种选择(在 .NET4 中可用)是使用 MemoryMappedFile(参见 http://msdn.microsoft.com/en-us/library/dd997372.aspx)——这样您根本不需要调用 Read :-)
https://stackoverflow.com/questions/6783848/