Amc*_*tty 2 c# casting filestream
我有一个关于从 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;
}
Run Code Online (Sandbox Code Playgroud)
简短的回答是:是的,这样您在处理任何长度 >= 2 GB 的文件时都会遇到问题!
如果您不希望有那么大的文件,那么您可以直接在 using 块的开头插入:
if (((int)fs.Length) != fs.Length) throw new Exception ("too big");
Run Code Online (Sandbox Code Playgroud)
否则,您不应该转换为 int,而是更改byte[] read = new byte[fsLength];
为byte[] read = new byte[fs.Length];并使用循环来读取 max 的“块”中的文件内容。每个块 2 GB。
另一种替代方案(.NET4 中提供)是使用 MemoryMappedFile(请参阅http://msdn.microsoft.com/en-us/library/dd997372.aspx) - 这样您根本不需要调用 Read :-)
| 归档时间: |
|
| 查看次数: |
1811 次 |
| 最近记录: |