日期:2014-05-17  浏览次数:21066 次

C# 支持docx上传
使用下面这个函数上传的时候 可以上传成功 但是docx格式有损坏 如何改善


  protected bool UpLoadFileStream(HttpPostedFile postfile, string saveFilePath)
  {
  System.IO.Stream iStream = null;
  // Buffer to read 10K bytes in chunk:
  byte[] buffer = new Byte[10000];
  int length = 0;
  // Total bytes to read:
  long dataToRead;
  Stream GetStream = postfile.InputStream;
  string fileName = System.IO.Path.GetFileName(postfile.FileName);
  //string filepath = Server.MapPath(saveFilePath + "\\" + fileName);
  if (File.Exists(saveFilePath) == false)
  {
  FileStream FS = new FileStream(saveFilePath, FileMode.CreateNew);
  BinaryWriter BW = new BinaryWriter(FS);
  try
  {
  dataToRead = GetStream.Length;//iStream.Length;
  while (dataToRead > 0)
  {
  // Verify that the client is connected.
  if (Response.IsClientConnected)
  {
  // Read the data in buffer.
  length = GetStream.Read(buffer, 0, 10000);

  // Write the data to the current output stream.
  BW.Write(buffer, 0, 10000);
  //buffer = new Byte[10000];
  dataToRead = dataToRead - length;
  }
  else
  {
  //prevent infinite loop if user disconnects
  dataToRead = -1;
  }
  }
  FS.Flush();
  FS.Close();
  BW.Flush();
  BW.Close();
  }
  catch
  {
  return false;
  }
  finally
  {
  if (iStream != null)
  {
  iStream.Close();
  }
  }
  }
  else
  {
  return false;
  }
  return true;
  }

------解决方案--------------------
我帮你重新组织了下代码,删掉了没用的部分,最重要的是,不要用 BinaryWriter 来写入,stream 直接就可以 write,就是 BinaryWriter 破坏的文件结构
C# code
protected bool UpLoadFileStream(HttpPostedFile postfile, string saveFilePath)
{
    if (File.Exists(saveFilePath))
    {
        return false;
    }

    try
    {
        using (FileStream FS = new FileStream(saveFilePath, FileMode.CreateNew))
        {
            byte[] buffer = new Byte[10000];
            int length = 0;
            while ((length = postfile.InputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                FS.Write(buffer, 0, length);
            }
        }
    }
    catch (Exception)
    {
        return false;
    }

    return true;
}

------解决方案--------------------
探讨
我帮你重新组织了下代码,删掉了没用的部分,最重要的是,不要用 BinaryWriter 来写入,stream 直接就可以 write,就是 BinaryWriter 破坏的文件结构