如果想要利用C#通过Socket进
行网络传输文件,一般情况下,大家会首先考虑使用.NET自带的Socket.SendFile Method
(String)这个方法。不过这个方法没有相应的文件接受方法,而且据说会有8KB的限制。所以,我尝试了另外一种方法,发现效果不错。下面,我就来简
单介绍一下其原理。
Socket.Send()和Socket.Receive()方法都是传递byte[]的,所以就要想办法把文件给变成byte[]。一开始试过用
StreamReader来读取string,然后用Encoding来进行编码得到byte[],接收以后再还原成string写入文件。结果发现不可
行,只有纯文本文件以这种方法传输是正常的。
无奈之下,只好另想办法。后来在File类下找到了这两个方法——File.ReadAllBytes()和
File.WriteAllBytes()。试了一下用这两个方法来把文件变成byte[],再把byte[]还原成文件,结果成功了!(试过了传输图片
和rar压缩文件,都OK!)
有兴趣的朋友,可以到这里下载源码:http://download.csdn.net/source/511058(原创代码)
网上有很多方案,起初用时,因为对asp.net不太了解,觉得FTP实现不错,可是后来发现,如果机器在域控下,就会有问题。
一年过去了,asp.net也熟悉了,知道ajax没事应该用ashx,验证码也用ashx,当然这里要说的WinForm上传也应该是ashx了 吧,哈哈,先提供简单思路:
接收文件的asp.net是:Uploader.ashx,相关代码:
usingSystem;
usingSystem.IO;
usingSystem.Web;
publicclassUploader : IHttpHandler
{
publicvoidProcessRequest(HttpContext hc)
{
foreach(stringfileKeyinhc.Request.Files)
{
HttpPostedFile file = hc.Request.Files[fileKey];
file.SaveAs(Path.Combine(hc.Server.MapPath("."), file.FileName));
}
}
publicboolIsReusable
{
get{returntrue; }
}
}
发送图片或文件的WinForm.cs 相关代码:
System.Net.WebClient myWebClient =newSystem.Net.WebClient();
myWebClient.UploadFile("http://www.yongfa365.com/Uploader.ashx","POST","C:\\WINDOWS\\system32\\cmd.exe");
OK,完了,这样操作后,再也不用管是不是在域控内了,只要能上网,就能上传。够方便吧。
如果你要批量上传,还有上传后保存在哪个目录等操作可以参考柳永法 (yongfa365)'Blog写的:
接收文件的asp.net是:Uploader.ashx,相关代码:
usingSystem;
usingSystem.IO;
usingSystem.Web;
publicclassUploader : IHttpHandler
{
publicvoidProcessRequest(HttpContext hc)
{
stringNowPath = Path.Combine(hc.Server.MapPath("."), hc.Request["path"]);
if(!Directory.Exists(NowPath))
{
Directory.CreateDirectory(NowPath);
}
foreach(stringfileKeyinhc.Request.Files)
{
HttpPostedFile file = hc.Request.Files[fileKey];
stringFilePath = Path.Combine(NowPath, file.FileName);
if(File.Exists(FilePath))
{
if(Convert.ToBoolean(hc.Request["overwrite"]))
{
File.Delete(FilePath);
}
else
{
continue;
}
}
file.SaveAs(FilePath);
}
}
publicboolIsReusable
{
get{returntrue; }
}
}
发送图片或文件的WinForm.cs 相关代码:
stringurl = @"http://www.yongfa365.com/Uploader.ashx?Overwrite