使用WebClient进行上传文件 [ZT]

   private bool UploadFile(string source,string targetUrl,NetworkCredential networkCredential)
        
{
            FileStream streamSource;
            Stream streamTarget;
            WebClient client 
= new WebClient();
            client.Credentials 
= networkCredential;
            
try
            
{
                streamSource 
= File.OpenRead(source);
            }

            
catch (Exception err)
            
{
                
return false;
            }

            
try
            
{
                Uri url 
= new Uri(targetUrl);
                streamTarget 
= client.OpenWrite(url, "PUT");
            }

            
catch (Exception err)
            
{
                
return false;
            }

            
try
            
{
                
long num = 0;
                
int count = 0;
                
byte[] buffer = new byte[512];
                
while (num < streamSource.Length)
                
{
                    count 
= streamSource.Read(buffer, 0512);
                    streamTarget.Write(buffer, 
0, count);
                    num 
+= count;
                    
                }

                streamTarget.Close();
                streamSource.Close();
                
return true;
            }

            
catch (Exception err)
            
{
                
return false;
            }

        }
 
posted @ 2007-10-18 12:39  RobotTech  阅读(398)  评论(0编辑  收藏  举报