应用场景:
项目需增加每分钟将实时统计数据写入文件后通过FTP发送给数据分析监管平台的功能,简单地写一下创建文件和FTP文件上传的小例子。
一、创建文件
FtpFileUpload ftpFileUpload = new FtpFileUpload();
/// <summary>
/// 创建文件
/// </summary>
/// <param name="psList">要写入文件的数据记录数组</param>
/// <param name="fileName">带有后缀名的文件名称</param>
public void SaveFile(List<string> psList, string fileName)
{
bool bResult = false;
string path = AppDomain.CurrentDomain.BaseDirectory + fileName;
string s = path.Substring(0, path.LastIndexOf('\\'));
if (! Directory.Exists(s))
{
Directory.CreateDirectory(s);//如果文件夹不存在就创建它
}
System.IO.FileStream FS = null;
System.IO.StreamWriter SW = null;
try
{
//新建文件流
FS = new System.IO.FileStream(
path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
//建立文件对应的输入流
SW = new System.IO.StreamWriter(FS);
//向输入流中写入信息
foreach (string ps in psList)
{
SW.Write(ps + "~\r\n");
}
bResult = true;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
bResult = false;
}
finally
{
if (SW != null)
{
SW.Close();
}
if (FS != null)
{
FS.Close();
}
if (bResult)
{
//FTP发送文件
ftpFileUpload.UploadFtp(path);
}
}
}
二、FTP文件上传
public class FtpFileUpload
{
public string ftpServerIP = "";
public string ftpUserID = "";
public string ftpPassword = "";
public string ftpFileRootPath = "";
public FtpWebRequest reqFTP;
public FtpFileUpload()
{
ftpServerIP = ConfigurationManager.AppSettings["FTPIPANDPort"];
string[] userPass = ConfigurationManager.AppSettings["FTPUserANDPassword"].Split(';');
// FTPFileRootPath ://Users//ftpFileTest//
ftpFileRootPath = ConfigurationManager.AppSettings["FTPFileRootPath"];
ftpUserID = userPass[0]