0

我创建了一个简短的代码,我得到了这个异常:

句柄不支持同步操作。FileStream 构造函数的参数可能需要更改以指示句柄是异步打开的(即,它是为重叠 I/O 显式打开的)。

代码是这样的:

byte[] filebytes = File.ReadAllBytes(filepath);
List<byte> codedbytes = new List<byte>();
byte constbyte = 240;
int blocksize = 67108864;
int counter = 0;
List<int> tempindex = new List<int>();
int index = 0;

private void DoTheJob()
{

        [...]

        for (int i = 0; i < filebytes.Length; i++,counter++)
        {
            codedbytes.AddRange(BitConverter.GetBytes(Convert.ToChar((filebytes[i] * constbyte))));
            if (counter == blocksize)
            {
                FileStream tempwriter = File.Create(startdir + "\\temp" + index.ToString() + ".file");

                for (int x = 0; x < codedbytes.Count; x++)
                {
                    tempwriter.WriteByte(codedbytes[x]);
                }

                tempwriter.Close();
                codedbytes.Clear();
                counter = 0; tempindex.Add(index); index++;
            }
        }

        [...]

        for (int x = 0; x < tempindex.Count; x++)
        {
            ▉Exception at this line▉▶ codedbytes = new List<byte>(File.ReadAllBytes(startdir + "\\temp" + tempindex[x].ToString() + ".file"));

            [...]
        }
}

我不知道是什么问题,因为 FileStrem 类没有重载的构造函数,并且我关闭了每个对象。

请告诉我正确的方法!

4

1 回答 1

0

我认为问题在于您只是关闭了 FileStream 而没有处理 FileStream。我在想可能有一个与关闭时未释放但可能与 Dispose 相关的文件的资源。异常提到的构造函数可能是在尝试执行 File.ReadAllBytes 时创建的 FileStream。

尝试这个:

private void DoTheJob()
{

        [...]

        for (int i = 0; i < filebytes.Length; i++,counter++)
        {
            codedbytes.AddRange(BitConverter.GetBytes(Convert.ToChar((filebytes[i] * constbyte))));
            if (counter == blocksize)
            {
                using (FileStream tempwriter = File.Create(startdir + "\\temp" + index.ToString() + ".file"))
                {
                    for (int x = 0; x < codedbytes.Count; x++)
                    {
                        tempwriter.WriteByte(codedbytes[x]);
                    }               
                }

                codedbytes.Clear();
                counter = 0; tempindex.Add(index); index++;
            }
        }

        [...]

        for (int x = 0; x < tempindex.Count; x++)
        {
            codedbytes = new List<byte>(File.ReadAllBytes(startdir + "\\temp" + tempindex[x].ToString() + ".file"));

            [...]
        }
}
于 2012-06-26T18:50:00.473 回答