FileStream fs=File.OpenRead(str);
或者
FileStream fs=new FileStream(str, FileMode.Open, FileAccess.Read, FileShare.Read);
这两句,经常都会崩溃,是因为文件已经被其它进程打开了.
我在想,为什么不是以下这样的机制?:当OpenRead()或者FileStream()尝试打开文件失败时,返回NULL.
这样的话,程序不会崩溃,而且我们可以判断是否打开失败.
现在的机制却是:打不开,程序就崩溃,太让人蛋疼了.怎么才能让OpenRead遇到已被打开的文件,不崩溃?

解决方案 »

  1.   


    try
                {
                    if (!File.Exists(path))
                    {
                        using (FileStream fs = File.Create(path))
                        {
                            Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                            fs.Write(info, 0, info.Length);
                        }
                    }                using (FileStream fs = File.OpenRead(path))
                    {
                        byte[] b = new byte[1024];
                        UTF8Encoding temp = new UTF8Encoding(true);                    while (fs.Read(b, 0, b.Length) > 0)
                        {
                            Console.WriteLine(temp.GetString(b));
                        }
                    }
                }
                catch 
                {
                    MessageBox.Show("文件已打开");
                }