我在阅读文件和子文件夹时遇到问题。对于给定的固定源路径E:\\Folder\\test\\test2
,我的代码读取正常。
测试中有许多文件夹,如test2,test3,test4等。我想在主文件夹test
中提取数据文件。
例如,我想在test中提取文件,所以我想读取测试中包含的所有文件,而不是编写test3,test4和许多代码。我想在另一个驱动器上提取和写入所有文件作为相同的源结构。
,如果源结构与E:\\Folder\\test\\test2
类似,那么目标结构应该像C:\\Folder\\test\\test2
有没有办法做到这一点?
这是我的代码,
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
DateTime dt = dateTimePicker1.Value;
txtSelectedDate.Text = dt.ToString("yyyyMMdd");
selectedDate = txtSelectedDate.Text;
}
private void button2_Click(object sender, EventArgs e)
{
DateTime stdate = Datetimepicker1.value;
while (stdate <= DateTime.Now)
{
txtSelectedDate.Text = stdate.ToString("yyyyMMdd");
selectedDate = txtSelectedDate.Text;
string DayBgSpot = "E:\\Folder\\test\\test2";
string DayBgSpotDestination = "E:\\Folder1";
int DT = int.Parse(txtSelectedDate.Text);
FileReader Reader = new FileReader();
FileReader Reader1 = new FileReader();
Reader.OpenDirectory(DayBgSpot);
Reader.ReadNaster();
string path = DayBgSpotDestination + "\\" + txtSelectedDate.Text + ".txt";
StreamWriter Strwriter = new StreamWriter(path);
try
{
while (Reader.iMaRecordsLeft > 0)
{
string SecName = Reader.sMaSecName;
string Symbol = Reader.sMaSecSymbol;
Symbol = prefix + Symbol;
int abc = 0;
Reader.OpenSecurityByName(Reader.sMaSecName);
if (Reader.iSeRecords > 0)
{
while (Reader.iSeRecordsLeft > 0)
{
Reader.ReadDay();
float O = Reader.dSeo;
float H = Reader.dSeh;
float L = Reader.dSel;
float C = Reader.dSec;
double V = Reader.dSeV;
double OI = Reader.dSrest;
string T = Reader.iSeTime.ToString();
string D = Reader.iSeDate.ToString();
if (int.Parse(D) == DT)
{
string a = string.Concat(SecName, ",", Symbol, ",", D, ",", T, ",", O, ",", H, ",", L, ",", C, ",", V, ",", OI);
if (SecName != "" && V != 0)
{
Strwriter.WriteLine(a);
}
}
}
}
abc++;
Reader.ReadNaster();
}
Reader.CloseDirectory();
Strwriter.Close();
Strwriter.Dispose();
}
catch
{
}
stdate = stdate.AddDays (1); // It will get next date till present
}
}
答案 0 :(得分:1)
像
这样的东西System.IO.DirectoryInfo baseFolder = new DirectoryInfo(@"c:\Folder\test\");
string destinationPath = @"e:\Folder\test\";
System.IO.DirectoryInfo[] subDirs = baseFolder.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
string subFolder = dirInfo.Name;
System.IO.FileInfo[] fileInfos = dirInfo.GetFiles("*.txt");
foreach (System.IO.FileInfo fileInfo in fileInfos)
{
// Do something with the files
string writePath = destinationPath + subFolder + @"\" + fileInfo.Name;
// Write
}
}
答案 1 :(得分:1)
如果您使用的是.NET 4.0,则只需一行:
var filepaths = Directory.GetFiles(path: @"C:\", searchPattern: "*pattern*", searchOption: SearchOption.AllDirectories);
显然,根路径和搜索模式与提议的样本不一致,但我的意图应该清楚。
我希望这会有所帮助