我现在有一个程序不断写excel文件。有什么好办法解决写excel文件的同时用户手动打开excel文件,程序会报文件被另一进程占用异常的错误。File.Open(FileSavePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);好像不行。谢谢。

解决方案 »

  1.   

    public static string LoadFile(string path)
            {
                if (!File.Exists(path)) return null;
                FileStream fs = null;
                for (int i = 0; i < 5; i++)//尝试打开5次
                {
                    try
                    {
                        fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                        break;
                    }
                    catch
                    {
                        Thread.Sleep(50);//暂停50毫秒
                    }
                }
                if (fs == null) throw new IOException("Unable to open the file: " + path);
                StreamReader sr = new StreamReader(fs, Encoding.Default);
                string res = sr.ReadToEnd();
                sr.Close();
                fs.Close();
                return res;
            }
      

  2.   

    用户打开前先COPY到指定一个目录吧。然后打开你指定目录下的EXCEL。读写两不误
     但是这么做就是有点浪费资源。每次都要COPY。。期待高手解决