模拟获取股票大小的过程

时间:2011-09-06 11:26:15

标签: c# exception file-io

我编写了一些代码来模拟获取共享驱动器大小的过程。驱动器来自文本文件。问题是路径到达超过250的阶段? charachter限制。无论如何,这是可以避免的。

我在网上找到了一些建议将@“\?\”放在文件路径之前但是如果它可以用于定义并且我是否正确使用它是不正确的?

谢谢

        void getSizes_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            String val = "";
            float megabytes = ((float)e.Result / 1024f) / 1024f;
            if (megabytes > 10240) //greater than 10 gig
                val = (megabytes / 1024.0).ToString() + "GB";
            else
                val = megabytes + "MB";
            textBox1.Text += val;
            textBox1.Text += Environment.NewLine;
        }

        void getSizes_DoWork(object sender, DoWorkEventArgs e)
        {
            String s = (String)e.Argument;
            String path = Path.GetFullPath(s);
            float bytes = (float)GetDirectorySize((String)e.Argument);
            e.Result = bytes;
        }

        protected static float GetDirectorySize(string folder)
        {
            float folderSize = 0.0f;
            try
            {
                //Checks if the path is valid or not
                if (!Directory.Exists(folder))
                    return folderSize;
                else
                {
                    try
                    {
                        foreach (string file in Directory.GetFiles(folder))
                        {
                            String path = @"\\?\" + file;
                            if (File.Exists(path))
                            {
                                FileInfo finfo = new FileInfo(path);
                                folderSize += finfo.Length;
                            }
                        }

                        foreach (string dir in Directory.GetDirectories(folder))
                            folderSize += GetDirectorySize(dir);
                    }
                    catch (NotSupportedException e)
                    {
                        Console.WriteLine("Unable to calculate folder size: {0}", e.Message);
                    }
                }
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("Unable to calculate folder size: {0}", e.Message);
            }
            return folderSize;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

有关路径长度和\\?\前缀的信息,请参阅http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx#maxpath

有关@""字符串的详细信息,请参阅http://msdn.microsoft.com/en-us/library/362314fe(v=vs.71).aspx

它应该为您提供有关该主题的更多信息,至少足以提出更具体的问题。