http://www.iloveyou10000.com

新blogs地址 http://itares.cnblogs.com

博客园 首页 新随笔 联系 订阅 管理

.NET 提供了许多上载文件的方法,在Windows Form应用程序中,我们可以使用WebClient类来实现。WebClient类也有两个方法可以上载,UploadFileOpenWrite方法,下面就是一个实际的例子,两种方法都有代码:

结果如下:

C#代码如下:

 
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Text;
using System.IO;


namespace UploadFile
{
  
public class Form1 : System.Windows.Forms.Form
  
{
    
private System.Windows.Forms.Label label1;
    
private System.Windows.Forms.Label label2;
    
private System.Windows.Forms.Button button1;
    
private System.Windows.Forms.Label label3;
    
private System.Windows.Forms.Button button2;
    
private System.Windows.Forms.TextBox txtFileName;
    
private System.Windows.Forms.TextBox txtServerPath;
    
private System.Windows.Forms.LinkLabel linkLabel1;
    
    
private System.ComponentModel.Container components = null;

    
public Form1()
    
{
      InitializeComponent();
    }

    
protected override void Dispose( bool disposing )
    
{
      
if( disposing )
      
{
        
if (components != null
        
{
          components.Dispose();
        }

      }

      
base.Dispose( disposing );
    }


    
Windows Form Designer generated code
    [STAThread]
    
static void Main() 
    
{
      Application.Run(
new Form1());
    }


    
/// <summary>
    
/// .NET SDK 上面的打开文件的类
    
/// </summary>


    
private FileStream OpenFile()
    
{
      OpenFileDialog dlgOpenFile 
= new OpenFileDialog();
      dlgOpenFile.ShowReadOnly 
= true;


      
if(dlgOpenFile.ShowDialog() == DialogResult.OK)
      
{
        
if(dlgOpenFile.ReadOnlyChecked == true)
        
{
          
return (FileStream)dlgOpenFile.OpenFile();

        }

        
else
        
{
          
string path = dlgOpenFile.FileName;
          
return new FileStream(path, System.IO.FileMode.Open, 
            System.IO.FileAccess.ReadWrite);
        }

      }

      
return null;
    }


    
private void button2_Click(object sender, System.EventArgs e)
    
{
      OpenFileDialog dlgOpenFile 
= new OpenFileDialog();
      dlgOpenFile.InitialDirectory 
= @"C:\";
      dlgOpenFile.ShowReadOnly 
= false;
      dlgOpenFile.ReadOnlyChecked 
= true;
      dlgOpenFile.Filter 
= "所有文件 (*.*)|*.*";
      
if(dlgOpenFile.ShowDialog() == DialogResult.OK)
      
{
        
if(dlgOpenFile.ReadOnlyChecked == true)
        
{
          txtFileName.Text 
= dlgOpenFile.FileName.ToString();
        }

      }

    }


    
private void button1_Click(object sender, System.EventArgs e)
    
{
      
// 需要注意的是:txtServerPath文件夹有匿名可写的权限。
      
// 可以自己定义新文件名字
      if(txtFileName.Text.Trim() == "" || txtServerPath.Text.Trim() == "")
      
{
        MessageBox.Show(
"请输入你要上载的文件名字!","错误:", MessageBoxButtons.OK,
                                                         MessageBoxIcon.Information); 
      }

      
else
      
{
        
/// 得到文件名,文件扩展名字,服务器路径
        string fileNamePath = txtFileName.Text.Trim();
        
string uriString = txtServerPath.Text.Trim();
        
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\"+ 1); 
        
string fileNameExt = fileName.Substring(fileName.LastIndexOf("."+ 1);
        
if(uriString.EndsWith("/"== false) uriString = uriString + "/";

        uriString 
= uriString + fileName;
        
/// 创建WebClient实例
        WebClient myWebClient = new WebClient();
        myWebClient.Credentials 
= CredentialCache.DefaultCredentials;

        
// 要上传的文件
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        
//FileStream fs = OpenFile();
        BinaryReader r = new BinaryReader(fs);
        
try
        
{
          
//使用UploadFile方法可以用下面的格式
          
//myWebClient.UploadFile(uriString,"PUT",fileNamePath);
          byte[] postArray = r.ReadBytes((int)fs.Length);
          Stream postStream 
= myWebClient.OpenWrite(uriString,"PUT");
          
if(postStream.CanWrite)
          
{
            postStream.Write(postArray,
0,postArray.Length);
            label1.Text 
= fileName + "上传成功!";
          }

          
else
          
{
            label1.Text 
= "文件目前不可写!";
          }

          postStream.Close();
          linkLabel1.Text 
= "查看上载的文件";
          
for(int i = linkLabel1.Links.Count - 1;i>-1;i--)
          linkLabel1.Links.Remove(linkLabel1.Links[i]);
          linkLabel1.Links.Add(
0,linkLabel1.Text.Length,uriString);          
        }

        
catch(WebException errMsg)
        
{
          label1.Text
="上传失败:" + errMsg.Message;
        }

      }

    }


    
private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
    
{
      
this.WindowState = FormWindowState.Minimized;
      
this.linkLabel1.Links[linkLabel1.Links.IndexOf(e.Link)].Visited = true;
      
string target = e.Link.LinkData as string;
      
if(null != target)
      
{
        System.Diagnostics.Process.Start(target);
      }

      
else
      
{    
        MessageBox.Show(
"请用浏览器访问:" + target);
      }

    }


    
private void Form1_Resize(object sender, System.EventArgs e)
    
{
      
if(this.WindowState == FormWindowState.Maximized) this.WindowState = FormWindowState.Normal;
    }


    
private void button1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    
{
      
if(txtFileName.Text.Trim() != "" && txtServerPath.Text.Trim() != "")
      label1.Text 
= "正在上传文件,请稍侯……!";
    }
  
  }

}


posted on 2006-06-14 17:25  fanrsh  阅读(326)  评论(0编辑  收藏  举报