首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileStream.BeginRead()的越界异常

FileStream.BeginRead()的越界异常
EN

Stack Overflow用户
提问于 2013-10-09 23:17:40
回答 1查看 958关注 0票数 0

因此,我构建了一个小应用程序来打开和监视一个文件的变化,并显示一个窗口表单。

但是,无论何时更新一个文件,当我第一次加载该文件时,它都会正常工作。

这是我正在使用的代码段,它告诉我:

代码语言:javascript
复制
Offset and length were out of bounds for the array or count is greater than the number of   elements from index to
the end of the source collection.

我不知道这种逻辑到底有什么问题,因为它应该运作得很好。在第一个加载时,m_lastFilePosition设置为0,并创建一个大小为预期大小的字节数组。

代码语言:javascript
复制
m_readingFile = true;
FileStream l_stream = new FileStream(m_fileToWatch, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
FileInfo l_info = new FileInfo(m_fileToWatch);
buffer = new byte[l_info.Length-m_lastFilePosition];

l_stream.BeginRead(buffer,
    (int)m_lastFilePosition,
    (int)(l_info.Length - m_lastFilePosition),
    new AsyncCallback(FileReadCallback),
    l_stream);

以前有人遇到过这种情况吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-10 02:14:24

这部分归功于汉斯·帕桑,因为他帮助我朝着正确的方向前进。

基本上,我将以前发布的代码更改为l_stream.Seek(m_lastFilePosition,SeekOrigin.Begin);然后将偏移量更改为0,这解决了我的问题。

就这样,为了解决这个问题。

代码语言:javascript
复制
        m_readingFile = true;
        l_stream = new FileStream(m_fileToWatch, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        FileInfo l_info = new FileInfo(m_fileToWatch);

        if (m_lastFilePosition < l_info.Length)
        {

            buffer = new byte[l_info.Length - m_lastFilePosition];

            l_stream.Seek(m_lastFilePosition, SeekOrigin.Begin);

            IAsyncResult result = l_stream.BeginRead(buffer,
                0,
                (int)(l_info.Length - m_lastFilePosition),
                new AsyncCallback(FileReadCallback),
                l_stream);
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19284451

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档