如何提交文档到ftp服务器上,如何将一个XML的文件直接写到FTP服务器上

近期使用了ftp的上传,想将数据库中的信息写成一个XML文件然后传送到到远端的FTP服务器上,一开始的做法是先在本地的临时文件夹中生成一个XML文件,再通过ftp传送到服务器上,然后删除临时文件夹,虽然这样也能实现传送的效果,但是总觉得这个过程有点绕,就想直接使用流的形式写到FTP中,而不需要通过本地中转的形式,主要的方法如下:

///

///

///

///

name="filename">要保存的文件名

///

name="tPlatformGuanLian">自定义的要保存的数据对象

private void WriteToXMLFile(string filename, PlatformGuanLian

tPlatformGuanLian)

{

FtpWebRequest req = null;

FTPTools ftp

= new

FTPTools();//自己定义的一个类,里面可以得到ftp的地址、端口号、用户名以及密码等信息,还用一些负责上传的方法

string uri =

"ftp://" +

ftp.FtpAddress + ":" +

ftp.FtpPort + ftp.FtpRoot +

"/" + “此处填写在ftp上要保存的名称”

FileStream

fs = null;

System.IO.MemoryStream streamTemp = new

System.IO.MemoryStream();

XmlTextWriter w = new XmlTextWriter(streamTemp,

Encoding.UTF8);

w.Formatting

= Formatting.Indented; //xml文件内容是按级别缩进

//下面开始生成文件的内容

w.WriteStartDocument(); //开始写xml,在最后有与之匹配的WriteEndDocument

w.WriteStartElement("ROOT");

w.WriteStartElement("BOOK");

w.WriteElementString("RESOURCEUNIQUEID",

tPlatformGuanLian.SysId);

w.WriteElementString("ISBN",

tPlatformGuanLian.ISBN);

w.WriteElementString("TITLE",

tPlatformGuanLian.Title);

w.WriteElementString("AUTHOR",

tPlatformGuanLian.Author);

DateTime dt

= tPlatformGuanLian.PublishDate;

//string.Format("yymmdd",dt);

w.WriteElementString("PUBLISHDATE",

dt.ToString("d"));//时间格式

2/27/2009

w.WriteElementString("PUBLISHER",

tPlatformGuanLian.Publisher);

w.WriteElementString("KEYWORD",

tPlatformGuanLian.Keywords);

w.WriteEndElement();

//结束Book

w.WriteEndElement();

//结束root

w.WriteEndDocument();

//下面的两句比较重要

w.Flush();//确保书写器更新到streamTemp中

streamTemp.Position = 0; // 重置流的位置,以便我们可以从头读取

long

length = streamTemp.Length;

req =

(FtpWebRequest)WebRequest.Create(uri);

req.UseBinary = true;

req.KeepAlive = false;

req.Credentials = new NetworkCredential(ftp.FtpUserName,

ftp.FtpPassword);

req.Method =

WebRequestMethods.Ftp.UploadFile;

req.ContentLength = length;

try

{

Stream stream = req.GetRequestStream();

int bufferLength = 2048; //2K缓冲

byte[] b = new byte[bufferLength];

int i = 0;  //临时变量

//写入数据

while ((i = streamTemp.Read(b, 0, bufferLength)) >

0)

{

stream.Write(b, 0, i);

}

stream.Dispose();

streamTemp.Dispose();

}

catch

(WebException ex)

{

//log.Error(String.Format("上传文件 {0}

的过程中出错。", uri), ex);

}

w.Close(); //完成xml文件的输出,关闭

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值