日期:2014-05-18  浏览次数:21087 次

WebClient上传文件异常
Uri uri = new Uri("http://172.16.102.37/seeyon/uploadService.do?method=processUploadService&senderLoginName=zhouquandang&token=" + a8_token.id + "");
  string fileName = "201149154759.xlsx";
  //写入数据流
  byte[] postdata = System.Text.Encoding.ASCII.GetBytes(string.Format("{0}writeInfo",DateTime.Now.ToString("yyyy-MM-dd HH:ss")));
  WebClient client = new WebClient();
  client.Credentials = CredentialCache.DefaultCredentials;
  FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  try
  {
  BinaryReader br = new BinaryReader(fs,new ASCIIEncoding());
  br.BaseStream.Position = 0;// Set Position to the beginning of the stream.
  try
  {
  byte[] postArray = br.ReadBytes((int)fs.Length);
  Stream postStream = client.OpenWrite(uri, "POST");
  if (postStream.CanWrite)
  {
  postStream.Write(postArray, 0, postArray.Length);
  MessageBox.Show(fileName + "上传成功");
  }
  else
  {
  MessageBox.Show("文件目录不可写");
  }
  postStream.Close();
  }
  catch (WebException errMsg)
  {
  MessageBox.Show("上传失败:" + errMsg.Message);
  }
  }
  catch (InvalidOperationException ioorx)
  {
  MessageBox.Show(ioorx.ToString());
  }

这个上传是在我的winform程序上通过java程序提供的方法上传到其文件夹下,运行后提示上传成功,但是实际上并没有上传上去。当我断点运行的时候在BinaryReader br = new BinaryReader(fs,new ASCIIEncoding());
出现异常:“br.BaseStream.ReadTimeout”引发了“System.InvalidOperationException”类型的异常
“br.BaseStream.WriteTimeout”引发了“System.InvalidOperationException”类型的异常
此流上不支持超时。
请问大家如何解决啊 谢谢了

------解决方案--------------------

------解决方案--------------------
用webclient的异步方法
------解决方案--------------------
还有webclient不支持超时设置,用webrequest代替
http://msdn.microsoft.com/zh-cn/library/d4cek6cc(v=VS.80).aspx
------解决方案--------------------
不知道楼主解决没有,这个是我以前写的一个上传方法
//参数的filename是要上传的文件名,path是要上传的文件在你本机的路径
private void uploadFile(string filename, string path)
{
result = false;
using (WebClient upload = new WebClient())
{
#region 没有用到这个方法|应该比现在的方法好
// Server URL
string uriString = "http://aaaaaa.com/upload/updata/" + filename;

string fileName = path;

FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] postArray = br.ReadBytes(Convert.ToInt32(fs.Length));
Stream postStream = upload.OpenWrite(uriString, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
result = true;
}
postStream.Close();
fs.Close();


#endregion
}
}