看看这个时间点,想必各种方法都尝试过了。
可以确定的是,并没有进程访问新创建的这个文件。
但是却一直报错。系统:windows server 2008 R2
环境:framework 3.5
        private void saveAs(DataRow data)
        {
            int attachid = data["AttachID"].ToInt();
            string fileName = data["FileName"].ToString();            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "*|*.*";
            sfd.FileName = fileName;
            sfd.FilterIndex = 0;
            //sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                if (sfd.OpenFile() != null)
                {
                    string sql = string.Format("select FileContent from FormAttachment where AttachID = {0}", attachid);
                    byte[] content = (byte[])DataBridge.WSS.ExecuteScalar(sql);
                    if (!File.Exists(sfd.FileName))
                    {
                        File.Create(sfd.FileName).Close();
                    }                    //System.IO.File.WriteAllBytes(sfd.FileName, content); //报错:正由另一进程使用,因此该进程无法访问此文件。
                    MemoryStream ms = new MemoryStream(content);
                    FileStream fs = new FileStream(sfd.FileName, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite);//报错:正由另一进程使用,因此该进程无法访问此文件。
                    ms.WriteTo(fs);
                    ms.Close();
                    fs.Close();
                }
            }
        }

解决方案 »

  1.   

    利用“C:\\Users\\Administrator\\Desktop\\半年度会22议提纲.doc”明文字符串形式当参数,可以创建文件,
    但利用变量便不行。
      

  2.   

    因为在if判断中,sfd.OpenFile()打开了那个文件,却没人关闭它。因此File.WriteAllBytes会出错。
    解决方法就是把它去掉就可以了。if (sfd.ShowDialog() == DialogResult.OK)
    {
        string sql = ...;
        byte[] content = (byte[])DataBridge.WSS.ExecuteScalar(sql);
        System.IO.File.WriteAllBytes(sfd.FileName, content); 
    }
      

  3.   

    msdn的解释:
    SaveFileDialog.OpenFile Methodpublic Stream OpenFile()Return Value
    Type: System.IO.Stream
    The read/write file selected by the user.Re:
    For security purposes, this method creates a new file with the selected name and opens it with read/write permissions. This can cause unintentional loss of data if you select an existing file to save to. To save data to an existing file while retaining existing data, use the File class to open the file using the file name returned in the FileName property.以上来自:
    http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.openfile.aspx

    我觉得你不需要自己在Create了。
      

  4.   

     if (sfd.OpenFile() != null) <--这做啥。。你这里OPen了下边当然不能保存了。 把这个去掉
                  
      

  5.   

    楼上全是正解,报错很明显了,如果你不知道何时关闭和释放,就用Using,或者手工关闭。