1:浏览文件
OpenFileDialog open = new OpenFileDialog()
if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox1.Text = open.FileName
}
2:验证URI地址
string URi = "http://192.168.0.222//www/"
WebRequest myWebRequest = WebRequest.Create(URi)
myWebRequest.Timeout = -1
try
{
WebResponse webResponse = myWebRequest.GetResponse()
Stream webStream = webResponse.GetResponseStream()
webStream.Close()
//开a始º?上¦?传ä?
UploadFile(this.textBox1.Text, URi,true)
}
catch(WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
MessageBox.Show("服¤t务?器¡Â响¨¬应®|错䨪误¨®,ê?请?检¨¬查¨¦毕运和¨ª服¤t务?器¡Â连¢?接¨®是º?否¤?正y常¡ê!ê?")
}
if (ex.Status == WebExceptionStatus.Timeout)
{
MessageBox.Show("服¤t务?器¡Â超?时º¡À!ê?")
}
}
3:上传方法
private void UploadFile(string fileNamePath, string uriString, bool IsAutoRename)
{
/瞎数皮/第̨²一°?步?:êo获?取¨?要°a上¦?传ä?的Ì?文?件t信?息¡é
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\")+1) //获?取¨?上¦?传ä?文?件t名?称?
string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower()//文?件t后¨®缀Áo:êo小?写¡磨差ä
string newName = fileName
Guid gg = Guid.NewGuid()
if (IsAutoRename == true)
{
newName = gg.ToString() + fileName.Substring(fileName.LastIndexOf("."))//文?件t新?的Ì?名?称?
}
//第̨²二t部?:êo处ä|理¤¨ªURI地Ì?址¡¤
if (uriString.EndsWith("/") == false)
{
uriString = uriString + "/"
}
uriString = uriString + newName//匹£¤配?要°a上¦?传ä?文?件t:êoURI+文?件t名?
//第̨²三¨y部?:êo创ä¡ä建¡§wenClient实º¦Ì例¤y
WebClient client = new WebClient()
client.Credentials = CredentialCache.DefaultCredentials //设¦¨¨置?进?行D身¦¨ª份¤Y验¨¦证¡è的Ì?网ª?络?凭?证¡è
//第̨²四?部?:êo利¤?用®?流¢¡Â来¤¡ä实º¦Ì现?文?件t上¦?传ä?
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.ReadWrite)//要°a上¦?传ä?的Ì?文?件t穿ä?件t文?件t流¢¡Â
BinaryReader br = new BinaryReader(fs)//以°?二t进?制?方¤?式º?读¨¢取¨?
byte[] postArray = br.ReadBytes((int)fs.Length)//当Ì¡À前¡ã流¢¡Â写¡ä入¨?二t进?制?
Stream postStream = client.OpenWrite(uriString, "PUT")//向¨°指?定¡§的Ì?地Ì?址¡¤写¡ä入¨?数ºy据Y
try
{
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length)
postStream.Close()
fs.Dispose()
MessageBox.Show("上¦?传ä?成¨¦功|!ê?")
}
else
{
postStream.Close()
fs.Dispose()
MessageBox.Show("上¦?传ä?失º¡ì败㨹!ê?")
}
}
catch(Exception ex)
{
postStream.Close()
fs.Dispose()
MessageBox.Show("上¦?传ä?文?件t异°¨¬常¡ê"+ex.Message)
throw ex
}
finally
{
postStream.Close()
fs.Dispose()
}
}
有很多方法1)利用Socket(TCP或UDP)
2)利用WebClinet,采用HTTP上传如纳掘
3)利用FTP协议上传
4)局域网渣核内,利用共享文件夹也可以实现上传
……
具体采用哪种方法,茄谈取决于文件服务支持哪种协议
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)