当前位置:网站首页>Local file upload FTP or remote directory
Local file upload FTP or remote directory
2022-06-13 07:03:00 【AndroidOrCSharp】
1. Upload to FTP
/// <summary>
/// Upload files FTP
/// </summary>
/// <param name="localFile"></param>
/// <param name="workDate"></param>
/// <param name="batchNo"></param>
/// <returns></returns>
public bool UploadFiles1(string localFile,string workDate,string batchNo)
{
string FTPServer = string.Empty;
string FTPPort = string.Empty;
string FTPUser = string.Empty;
string FTPPwd = string.Empty;
string SendDir = string.Empty;
string dir = string.Empty;
FileStream fs = null;
Stream strm = null;
try
{
GetFTPServerCfg("0004", ref FTPServer, ref FTPPort, ref FTPUser, ref FTPPwd,ref SendDir);
FileInfo fileInf = new FileInfo(localFile);
dir = "ftp://" + FTPServer + "/" + SendDir + "/"+ workDate + "_" + batchNo;
string uri = "ftp://" + FTPServer + "/" + SendDir + "/" + workDate + "_" + batchNo +"/"+ fileInf.Name;
MakeDir(dir, reqFTP, FTPUser, FTPPwd);
Connect(uri, FTPUser, FTPPwd);
// The default is true, The connection won't be closed
// Executed after a command
reqFTP.KeepAlive = false;
// Specify what command to execute
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Notify the server of the size of the file when uploading it
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Open a file stream (System.IO.FileStream) To read the uploaded file
fs = fileInf.OpenRead();
// Write the uploaded file to the stream
strm = reqFTP.GetRequestStream();
// Every time I read the file stream kb
contentLen = fs.Read(buff, 0, buffLength);
// Stream content doesn't end
while (contentLen != 0)
{
// Take the content from file stream write in upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
return true;
}
catch (Exception ex)
{
//SystemMessge.Warning(ex.Message, " Upload error ");
return false;
}
finally
{
// Close both streams
if (strm != null)
{
strm.Close();
}
if (fs != null)
{
fs.Close();
}
}
}
/// <summary>
/// Create folder
/// </summary>
public void MakeDir(string uri, FtpWebRequest reqFTP, string ftpUserID, string ftpPassword,string fileName)
{
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);// Chinese file name
// Determine whether the folder exists Create... If it doesn't exist ( Only one level directory can be created )
string line = reader.ReadLine();
while (line != null)
{
if (line.Contains(fileName))
{
response.Close();
reader.Close();
return;
}
line = reader.ReadLine();
}
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.UseBinary = true;
response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
reader.Close();
response.Close();
}
catch (Exception ex)
{
}
}
#region Connect to server
/// <summary>
/// Connect to server
/// </summary>
/// <param name="path">FTP Address </param>
/// <param name="ftpUserID"> user name </param>
/// <param name="ftpPassword"> password </param>
private void Connect(String path ,string ftpUserID,string ftpPassword)
{
// according to uri establish FtpWebRequest object
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// Specify the data transfer type
reqFTP.UseBinary = true;
// ftp User name and password
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
}
#endregion
2. Upload to remote directory
// Complete one TANO The corresponding instructions are uploaded to FTP
Dir += "\\" + WorkDate + "_" + BatchNo;
List<FileInfo> files = new List<FileInfo>();
// Get all the files that need to be uploaded under the folder
files.AddRange(new DirectoryInfo(Dir).GetFiles());
log.Info(string.Format(" Start to execute the function of uploading the local remittance instruction to the remote server "));
GetFTPServerCfg("0005", ref FTPServer, ref FTPPort, ref FTPUser, ref FTPPwd, ref SendDir);
SendDir = @"\\" + FTPServer + @"\" + SendDir + WorkDate + "_" + BatchNo;
// Determine whether the remote folder exists , Create if it does not exist
if (!Directory.Exists(SendDir))
{
Directory.CreateDirectory(SendDir);
}
foreach (FileInfo file in files)
{
UploadFiles(Dir+"\\"+file.Name,SendDir, file.Name);
}
/// <summary>
/// Upload files FTP
/// </summary>
/// <param name="localFile"></param>
/// <param name="SendDir"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public void UploadFiles(string localFile, string SendDir,string fileName)
{
// establish WebClient example
File.Copy(localFile, SendDir + "/" + fileName, true);
}
边栏推荐
- SDN基本概述
- 基于FPGA的ds18b20温度传感器使用
- [cloud native | kubernetes] kubernetes configuration
- [system analysis and design] college student association management system
- Smart finance is upgraded again, and jinglianwen technology provides data collection and labeling services
- 2022-06-12:在N*N的正方形棋盘中,有N*N个棋子,那么每个格子正好可以拥有一个棋子。 但是现在有些棋子聚集到一个格子上了,比如: 2 0 3 0 1 0 3 0 0 如上的二维数组代表,一
- RT thread simulator lvgl control: switch switch button control
- Tidb implementation plan -- III
- 10 Honest Facts I Want To Share With All Junior Developers
- ML之FE:Vintage曲线/Vintage分析的简介、计算逻辑、案例应用之详细攻略
猜你喜欢
Yolov5 analysis | parameters and performance indicators
[system analysis and design] college student association management system
Nfv basic overview
Jinglianwen Technology: current situation and solutions of data annotation industry
Computer network interview questions
New Taishan crowdfunding business diversion fission growth model in 2022
Fe of mL: introduction to vintage curve /vintage analysis, calculation logic and detailed introduction to case application
16、 IO stream (II)
Chain 2+1 reward, what kind of mode is beautiful everyday seconds?
对绘制丘岭密度图ridge plot的详细说明、重叠核密度估计曲线overlapping densities、FacetGrid对象、函数sns.kdeplot、函数FacetGrid.map
随机推荐
Ansible PlayBook的中清单变量优先级分析及清单变量如何分离总结
Gold jewelry enterprise operation mode, beautiful tiantians business solution
Yolov5 analysis | parameters and performance indicators
【腾讯阿里最全面试题集锦】(四面:3轮技术+1轮HR)
Implementation of fruit mall wholesale platform based on SSM
微隔离(MSG)
想进行快速钢网设计,还能保证钢网质量? 来看这里
Tidb execution plan -- II
Detailed description of drawing ridge plot, overlapping densities of overlapping kernel density estimation curve, facetgrid object and function sns Kdeplot, function facetgrid map
Lightning data import
Project analysis of Taishan crowdfunding mode: why is Taishan crowdfunding mode so popular?
Jinglianwen Technology: current situation and solutions of data acquisition and labeling industry
How to use Wangyou DFM software for cold plate analysis
不间断管理设计
Xiaomi's one-sided interview questions (self sorting answers)
在 localStorage 中上传和检索存储图像
As the new trend of blind box e-commerce, how can the platform use blind box play to drain at low cost?
RT thread simulator lvgl control: button button style
杭州网上开户是安全的吗?
Differences between SQL and NoSQL of mongodb series