c# - 将文件流长度转换为 int

我对从 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/

相关文章:

r - 如何对字符向量的每个元素中的字符进行排序?

scala - Scala 中的可观察 map

oracle - 我可以更改 Oracle 中的隔离级别吗?

css - 通过 CSS 为仅带换行符的文本设置背景颜色

.net - 有人使用 Amazon EC2 + SQL Azure 吗?

google-chrome - 谷歌浏览器 Cookie 扩展 : "Cannot call met

assembly - : operator do in assembly? 是什么

c# - 我怎样才能得到列表的一半元素?

php - 使用 Session 或 Cookie 登录

scala - 是否可以对变量使用 match scala 操作?