文件流错误? .NET 2.0 [英] Filestream bug? .net 2.0

查看:99
本文介绍了文件流错误? .NET 2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解决使用文件流读取的方法的奇怪行为.文件流对象长度有时与实际文件长度不同.如果在调试开始后调用了该方法,则该方法将始终无法正常工作.如果我首先为相同的路径但不同的文件调用打开的文件对话框,则对象长度是正确的,直到程序停止并重新启动.两种方法之间没有连接,只是它们使用相同的目录.似乎正在多次读取文件.即使文件长度错误,它也不会引发错误.是否存在一些已知的文件流错误?

这是方法.

I am struggling with strange behavior of a method using filestream read. The filestream object length is sometimes different from the actual file length. If the method is called after starting in debug then it consistently doesn''t work right. If I call an open file dialog for the same path but different file first then the object length is correct until the program is stopped and restarted. There is no connection between the two methods except they use the same directory. It appears that it is reading the file more than once. It never throws an error even when the file length is wrong. Is there some known filestream bug?

Here''s the method.

private List<ushort> loadDesignFiles(string ext)
       {
           ushort[] intbuf = new ushort[1];
           const int MSB = 0;
           const int LSB = 1;
           int groupNum;
           FileInfo[] fi = null;

           DirectoryInfo dir = new DirectoryInfo(userDirectory);

           try
           {
               fi = dir.GetFiles("*." + ext);
               //clear all previous files
               desAllGroups.Clear();

               foreach (FileInfo thisFi in fi)
               {
                   //get group number from the file
                   int.TryParse(thisFi.ToString().Substring(5, 2), out groupNum);

                   FileStream inFile = new FileStream(thisFi.ToString(), FileMode.Open);

                   //This buffer is half the length of the input file
                   //since it is the combination of every two bytes
                   intbuf = new ushort[inFile.Length / 2];
                   byte[] wordbuf = new byte[2];

                   //combine every two consecutive bytes into int16
                   //low address is MSByte plus design curve number, next is LSByte
                   //MSB upper 4 bits contain design curve number in D14, D13 (0-3)

                   for (int j = 0; j < intbuf.Length; j++)
                   {
                       inFile.Read(wordbuf, 0, 2);
                       intbuf[j] = (ushort)(wordbuf[LSB] | (wordbuf[MSB] << 8));
                   }

                   //close file after use
                   inFile.Close();
                   //concat all groups
                   //new curves start a multiples of 2010d (7DAh)
                   //first char in each curve file is curve number
                   desAllGroups.AddRange(intbuf);
               }
           }
           catch (IOException ex)
           {
               MessageBox.Show(ex.Message);
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message);
           }

           if (desAllGroups.Count == 0)
               MessageBox.Show("No Design Files Found", "Warning");
           else MessageBox.Show("Loaded " + fi.Length + " Design Files", "Note");
           return desAllGroups;
       }

推荐答案

我个人从未见过此特定问题,但我见过其他开发人员编写的代码,这些开发人员不得不重视文件流长度(可能是由于您正在谈论的问题).

我会通过两种可能的方式进行处理:

1)尝试使用FileInfo.Length(例如thisFi.Length)

2)捕获Read的返回值,并使用它继续读取直到数据用完.

顺便说一句,没有必要使用intbuf,因为您只是将这些值添加到List< ushort>中.只需要一个ushort局部变量并将其立即添加到列表中即可.其次,我将对FileStream使用using语句,以确保您及时关闭文件.希望对您有所帮助.
I''ve personally never seen this particular issue, but I''ve seen code written by other developers who had to santize the value of the file stream length (probably due to the issue you are talking about).

I''d approach it from two possible ways:

1) Try using FileInfo.Length (e.g. thisFi.Length)

2) Capture the return value of Read and use it to just keep reading until you''re out of data.

Btw, there''s no reason for the intbuf as you''re just adding the values to the List<ushort>. Just have one ushort local variable and add that immediately to the list. Secondly, I''d use a using statement for the FileStream to ensure you close your files out in a timely manner. I hope that helps.


感谢您的快速回复.
好吧,就在我发布此消息后,我就找到了问题的原因.它忽略了我给它的目录路径,而是在\ bin \ debug文件夹中读取了几个碰巧具有相同名称的文件.我换了线

FileStream inFile =新的FileStream(userDirectory + thisFi.ToString(),FileMode.Open);

添加正确的目录并对其进行修复.


您对intbuf的评论使我提出了第二个问题.我真的很想为找到的每个文件创建一个单独的列表.有没有一种方法可以在循环中进行列表声明,从而可以为每个列表(例如listFile1,listFile2等)创建唯一的标识符,或者我是否需要创建列表的向量数组?
Thanks for the quick reply.
Well, just after I posted this I found the reason for the problem. It is ignoring the dir path that I give it and reading a couple of files in the \bin\debug folder that happen to have the same names. I changed the line

FileStream inFile = new FileStream(userDirectory+thisFi.ToString(), FileMode.Open);

to add the correct directory and that fixed it.


Your comment about intbuf leads me to a second question. I really want to create a separate list for each file found. Is there a way to make a list declaration in a loop that can create a unique identifier for each list (such as listFile1, listFile2 etc) or do I need to create an vector array of lists?


您将执行以下操作.我确实注意到您的原始代码存在for循环未遍历"Length/2"的问题.因此,这也可能给您带来一些问题.另外,使用此代码,您将需要验证以下内容:

-文件大小写结尾处理正确.
-byte到ushort的转换对您的情况有效(即,小端优先与大端优先)-我相信是这样,但请仔细检查.

You would do something like the following. I did notice your original code had an issue with the for loop not iterating over "Length / 2". So, that may have given you some of your problems as well. Plus, with this code, you''ll want to verify the following:

-End of file case is handled properly.
-Byte to ushort conversion is valid for your case (ie. little endian vs. big endian) - I believe it is, but double check.

private Dictionary<string, List<ushort>> loadDesignFiles(string ext)
{
    Dictionary<string, List<ushort>> dctAllGroups;
    List<ushort> lstWords;
    byte[] wordbuf;
 
    dctAllGroups = new Dictionary<string, List<ushort>>();
    wordbuf = new byte[2];
 
    foreach (string strFileName in Directory.GetFiles(userDirectory, "*." + ext))
    {
        dctAllGroups[strFileName] = lstWords = new List<ushort>();

        using (FileStream inFile = File.OpenRead(strFileName))
        {
            while (inFile.Read(wordbuf, 0, 2) == 2)
            {
                // Combine every two consecutive bytes into uint16
                lstWords.Add(BitConverter.ToUInt16(wordbuf, 0));
            }
        }
    }
 
    if (dctAllGroups.Count == 0)
        MessageBox.Show("No Design Files Found", "Warning");
    else
        MessageBox.Show("Loaded " + dctAllGroups.Count + " Design Files", "Note");
 
    return dctAllGroups;
}


您开发和阅读其他人的代码越多,您所得到的就会越好.只是呆在那里.


The more you develop and read other people''s code, the better you''ll get. Just keep in there.


这篇关于文件流错误? .NET 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆