高手帮忙!!WebClient怎么用!

gaoweipeng7851 2008-11-03 07:44:57
我向实现文件的上传和下载的功能,不利用asp.net的上传控件(软件需要)
想利用WebClient来实现
但是不知道WebClient到底得怎么写啊?我是这么写的,但是会报错:
protected void Button1_Click(object sender, EventArgs e)
{
WebClient aa = new WebClient();
aa.Credentials = CredentialCache.DefaultCredentials;
string uriString = "http://localhost:1063/Texttt/test.txt";//这里用server.mapth的话就会报文件夹不能访问 string fileName = @"c:\tmp\test.txt";
//wb.UpFile(uriString, fileName);

aa.UploadFile(uriString, fileName);
aa.Dispose();
}

远程服务器返回错误(504)不允许的方法!
我看了论坛里很多类似的帖子,但是都没有好的解决方案,高手在哪里??
项目急用,高分求助!

...全文
905 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuyq11 2008-11-13
  • 打赏
  • 举报
回复
public string UploadFile(string fileNamePath,string uriString)
{
string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
string NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));
string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
if(uriString.EndsWith("/") == false)
{
uriString = uriString + "/";
}
uriString = uriString + NewFileName;
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
try
{
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString,"PUT");
if(postStream.CanWrite)
{
postStream.Write(postArray,0,postArray.Length);
}
else
{
return "NO";
}
postStream.Close();
return "Succefull";
}
catch(Exception ex)
{
return "Error:" + ex.Message;
}
}
public string Download(string URL,string Dir)
{
WebClient client = new WebClient();
string fileName = URL.Substring(URL.LastIndexOf("/") + 1);
string Path = Dir+fileName; try
{
WebRequest myre=WebRequest.Create(URL);
}
catch(Exception ex)
{
return "Error:" + ex.Message;
}
try
{
client.DownloadFile(URL,Path);
return "Succefull";
}
catch(Exception ex)
{
return "Error:" + ex.Message;
}
}
gaoweipeng7851 2008-11-13
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 zhoufoxcn 的回复:]
如果是HTTP方式上传,则需要编写服务器的处理代码。
如果是FTP服务器则不需要,直接通过FTP协议上传了。
[/Quote]

如果代码要在服务器端执行,那么明明是要在客户端的c:...下找文件,是不要在服务器的c;....下找文件了啊??
hongqi162 2008-11-06
  • 打赏
  • 举报
回复
        public static bool UploadFile(string localFilePath, string serverFolder,bool reName)
{
string fileNameExt, newFileName, uriString;
if (reName)
{
fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf(".") + 1);
newFileName = DateTime.Now.ToString("yyMMddhhmmss") + fileNameExt;
}
else
{
newFileName = localFilePath.Substring(localFilePath.LastIndexOf(@"\")+1);
}
if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith(@"\"))
{
serverFolder = serverFolder + "/";
}

uriString = serverFolder + newFileName; //服务器保存路径
/**//// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;

// 要上传的文件
FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
try
{
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(uriString,"PUT",localFilePath);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
else
{
//MessageBox.Show("文件目前不可写!");
}
postStream.Close();
}
catch
{
//MessageBox.Show("文件上传失败,请稍候重试~");
return false;
}

return true;
}

/**//// <summary>
/// 下载服务器文件至客户端
/// </summary>
/// <param name="uri">被下载的文件地址</param>
/// <param name="savePath">另存放的目录</param>
public static bool Download(string uri, string savePath)
{
/**url 文件名解析
string fileName; //被下载的文件名
if (uri.IndexOf(@"\") > -1)
{
fileName = uri.Substring(uri.LastIndexOf(@"\") + 1);
}
else
{
fileName = uri.Substring(uri.LastIndexOf("/") + 1);
}
if (!savePath.EndsWith("/") && !savePath.EndsWith(@"\"))
{
savePath = savePath + "/";
}
savePath += fileName; //另存为的绝对路径+文件名
* */
WebClient client = new WebClient();
try
{
client.DownloadFile(uri, savePath);
}
catch
{
return false;
}

return true;
}
IMAGSE 2008-11-06
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 cpio 的回复:]
上传不是说直接就可以上传的,它不像FTP,或者,你可以考虑FTP,连到FTP的话,可以这样传

如果要用HTTP的话,需要在服务器端写代码
[/Quote]

是的~
周公 2008-11-06
  • 打赏
  • 举报
回复
下面的代码示例使用 UploadFile 将指定的文件上载到指定的 URI。由服务器返回的任何响应都显示到控制台。
客户端的代码:

Console.Write("\nPlease enter the URI to post data to : ");
String uriString = Console.ReadLine();

// Create a new WebClient instance.
WebClient myWebClient = new WebClient();

Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URI");
string fileName = Console.ReadLine();
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);

// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);

// Decode and display the response.
Console.WriteLine("\nResponse Received.The contents of the file uploaded are:\n{0}",
System.Text.Encoding.ASCII.GetString(responseArray));


服务器的代码:

<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {

foreach(string f in Request.Files.AllKeys) {
HttpPostedFile file = Request.Files[f];
file.SaveAs("c:\\inetpub\\test\\UploadedFiles\\" + file.FileName);
}
}

</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>
周公 2008-11-06
  • 打赏
  • 举报
回复
如果是HTTP方式上传,则需要编写服务器的处理代码。
如果是FTP服务器则不需要,直接通过FTP协议上传了。
cpio 2008-11-04
  • 打赏
  • 举报
回复
上传不是说直接就可以上传的,它不像FTP,或者,你可以考虑FTP,连到FTP的话,可以这样传

如果要用HTTP的话,需要在服务器端写代码
宝_爸 2008-11-03
  • 打赏
  • 举报
回复
不使用fileupload上传文件
參考一

How To Send a Binary Stream by Using XMLHTTP
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q296772

參考二

AJAX file upload
http://www.codeproject.com/useritems/AJAXUpload.asp


參考三

Client : VBS Server : ASP.NET



VBS上傳



filename = "c:\psexec.exe"

Set ado_stream = CreateObject("ADODB.Stream")

ado_stream.Type = 1 '1=adTypeBinary

ado_stream.Open

ado_stream.LoadFromFile(filename)



Set xmlhttp = CreateObject("Microsoft.XMLHTTP")

xmlhttp.open "POST","http://localhost/ReadFile/webform1.aspx?filename=" & Right(filename,Len(filename)-InstrRev(filename,"\")), False



xmlhttp.setRequestHeader "Content-Length", ado_stream.Size

xmlhttp.send(ado_stream.Read(ado_stream.Size))

wscript.echo xmlhttp.ResponseText













WebForm1.aspx 接收寫入



using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.IO;



namespace ReadFile

{

/// <summary>

/// WebForm1 的摘要描述。

/// </summary>

public class WebForm1 : System.Web.UI.Page

{

private void Page_Load(object sender, System.EventArgs e)

{

// 在這裡放置使用者程式碼以初始化網頁

string FILE_NAME = "C:\\Inetpub\\wwwroot\\ReadFile\\" + Request.QueryString["filename"];





FileStream fs = new FileStream(FILE_NAME, FileMode.Create);

BinaryWriter w = new BinaryWriter(fs);



const int BUFFER_SIZE = 255;

int nBytesRead = 0;

Byte[] Buffer = new Byte[BUFFER_SIZE];



Stream theStream = Request.InputStream;

nBytesRead = theStream.Read(Buffer, 0, BUFFER_SIZE);



while (0 != nBytesRead)

{

w.Write(Buffer,0,nBytesRead);

nBytesRead = theStream.Read(Buffer,0,BUFFER_SIZE);

}



w.Close();

fs.Close();

Response.Write("上傳完成");

}









#region Web Form 設計工具產生的程式碼

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: 此為 ASP.NET Web Form 設計工具所需的呼叫。

//

InitializeComponent();

base.OnInit(e);

}



/// <summary>

/// 此為設計工具支援所必須的方法 - 請勿使用程式碼編輯器修改

/// 這個方法的內容。

/// </summary>

private void InitializeComponent()

{

this.Load += new System.EventHandler(this.Page_Load);

}

#endregion

}

}

loworth 2008-11-03
  • 打赏
  • 举报
回复
http://dev.csdn.net/article/20/20135.shtm

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧