C# 如果需要,如何使用FileInfo[]或字符串[]?
在form1中,我有两个按钮,一个用于从单个文件或多个文件的目录中选择文件。 第二个按钮是从目录中选择文件,以获取所选目录中的所有文件 现在,我有一个类用于将文件/目录上载到我的ftp: 在全班最优秀的时候,我做到了:C# 如果需要,如何使用FileInfo[]或字符串[]?,c#,.net,winforms,C#,.net,Winforms,在form1中,我有两个按钮,一个用于从单个文件或多个文件的目录中选择文件。 第二个按钮是从目录中选择文件,以获取所选目录中的所有文件 现在,我有一个类用于将文件/目录上载到我的ftp: 在全班最优秀的时候,我做到了: public static DirectoryInfo d; public static string[] files; private FileInfo[] dirflist; 然后我在活动中使用它: private void FtpProgress_DoWork(objec
public static DirectoryInfo d;
public static string[] files;
private FileInfo[] dirflist;
然后我在活动中使用它:
private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
{
try
{
dirflist = d.GetFiles();
//if (dirflist.Length > 0)
//{
foreach (string txf in files)
{
string fn = txf;//txf.Name;
BackgroundWorker bw = sender as BackgroundWorker;
f = e.Argument as FtpSettings;
string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(fn));//f.SourceFile));
if (!UploadPath.ToLower().StartsWith("ftp://"))
UploadPath = "ftp://" + UploadPath;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);
request.UseBinary = true;
request.UsePassive = f.Passive;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Timeout = 300000;
request.Credentials = new NetworkCredential(f.Username, f.Password);
long FileSize = new FileInfo(f.SourceFile).Length;
string FileSizeDescription = GetFileSize(FileSize);
int ChunkSize = 4096, NumRetries = 0, MaxRetries = 50;
long SentBytes = 0;
byte[] Buffer = new byte[ChunkSize];
using (Stream requestStream = request.GetRequestStream())
{
using (FileStream fs = File.Open(f.SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
int BytesRead = fs.Read(Buffer, 0, ChunkSize);
while (BytesRead > 0)
{
try
{
if (bw.CancellationPending)
return;
requestStream.Write(Buffer, 0, BytesRead);
SentBytes += BytesRead;
string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(SentBytes), FileSizeDescription);
bw.ReportProgress((int)(((decimal)SentBytes / (decimal)FileSize) * 100), SummaryText);
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.ToString());
if (NumRetries++ < MaxRetries)
{
fs.Position -= BytesRead;
}
else
{
throw new Exception(String.Format("Error occurred during upload, too many retries. \n{0}", ex.ToString()));
}
}
BytesRead = fs.Read(Buffer, 0, ChunkSize);
}
}
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
System.Diagnostics.Debug.WriteLine(String.Format("Upload File Complete, status {0}", response.StatusDescription));
}
//}
}
catch (WebException ex)
{
switch (ex.Status)
{
case WebExceptionStatus.NameResolutionFailure:
ConnectionError = "Error: Please check the ftp address";
break;
case WebExceptionStatus.Timeout:
ConnectionError = "Error: Timout Request";
break;
}
}
}
但我不想再为string[]或FileInfo[]复制所有代码
我想制作一些东西,使我能够将FileInfo[]与foreach或foreach中的字符串[]一起使用
也许有时候我会上传多个文件,然后上传一个包含所有文件的目录
因此,复制整个代码并使用once string[]和once FileInfo[]可能更好?
我的意思是创建两个方法,一个使用FileInfo[]一个字符串[]将处理单个文件的所有代码放在一个单独的方法中,如下所示:
private void CopyFile(string fn)
{
BackgroundWorker bw = sender as BackgroundWorker;
f = e.Argument as FtpSettings;
...
}
现在决定是执行文件列表还是执行目录列表,并按如下方式调用新方法:
private void CopyFile(string fn)
{
BackgroundWorker bw = sender as BackgroundWorker;
f = e.Argument as FtpSettings;
...
}
文件列表:
foreach (string txf in files)
{
this.CopyFile(txt);
}
dirflist = d.GetFiles();
if (dirflist.Length > 0)
{
foreach (FileInfo txf in dirfilist)
{
this.CopyFile(txt.Name);
}
}
目录列表:
foreach (string txf in files)
{
this.CopyFile(txt);
}
dirflist = d.GetFiles();
if (dirflist.Length > 0)
{
foreach (FileInfo txf in dirfilist)
{
this.CopyFile(txt.Name);
}
}
如果需要,如何使用FileInfo[]
或字符串[]
然后可以通过传递所需的任何参数来重载函数GetMyFiles
string[] GetMyFiles(String DirectoryPath)
// Returns an Array of String that contains all the Files in the Directory.
string[] GetMyFiles(FileInfo MyFileInfo)
// Returns an Array of String with just one File Path.
string[] GetMyFiles()
// Opens a MultiSelect OpenFileDialog,
// then returns the selected Files Path in an Array (or empty Array)
// ...
另一种方法是:将代码分为多个部分,然后通过条件检查决定要使用的部分
private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
{
// Do the maximum you can do here...
// ...
if ImGoingToUseStringArray
{
string[] files = ....
ResumeWithStringArray(files, sender, e);
}
else
{
FileInfo[] dirflist = ....
ResumeWithFileInfo(dirfList, sender, e);
}
}
private void ResumeWithStringArray(string[] files, object sender, DoWorkEventArgs e)
{
// ...
// you can also call another core Function from here
sendMyFile(args)
}
private void ResumeWithFileInfo(FileInfo[] dirflist, object sender, DoWorkEventArgs e)
{
// ...
// you can also call another core Function from here
sendMyFile(args)
}
无论如何,您必须使用FileInfo来获得文件大小(我认为在文件传输中是必需的),对吗?但是,您可以决定何时为每个文件创建FileInfo(或者您是否同时使用多个FileInfo-s?)
在我看来,您的问题的答案只取决于您的品味,或者只需要对您运行逻辑的方式进行一些更改。只需使用
d.GetFileSystemInfos()
-您在提问之前查看了所有内容吗?我已经阅读了Ftp发送过程。我会将任务划分为函数。虽然包含CancellationPending Handling的函数是一个函数(如果文件已处理,则返回1;如果BW取消,则返回0;如果出现异常,则可能返回-1),但我还将移动该任务以在函数中获取每个文件路径(或FileInfo)的文件信息,该函数返回一个包含所有必需成员的自定义类(然后只需将该类传递给将处理缓冲的函数即可)-出于UI目的,此类类可以包含缓冲、处理FTP发送和引发事件:chunck send、transfer complete、cancelled。。。