我在Debug \ Tests \ Text \(10个txt文件)中有10个txt文件。我需要编写一个程序来打开所有10个文件并更新每个文件。我不知道怎么做。现在,我实际上正在读取文件夹并获取文件名并将文件名存储在一个数组中。以下是我的代码:
private void getFilesName()
{
string[] fileArray = Directory.GetFiles(@"Tests\Text");
//looping through the folder and get the fileNames
for (int i = 0; i<fileArray.Length; i++)
{
MessageBox.Show(fileArray[i]); // I'm doing this is to double check i manage to get the file name.
}
}
执行此操作后,它会读取所有文本文件名,但现在的挑战是我访问文件名并更新其中的每个文件。我还创建了另一种方法来更新txt文件中的值,下面是代码:
private bool modifySQLFile()
{
string destFileName = @"Tests\Text\" // I need the fileName?
string[] fileTexts = File.ReadAllLines(destFileName);
int counter = 0;
//Processing the File
foreach(string line in fileTexts)
{
//only read those non-comments line
if(line.StartsWith("--") == false)
{
//Start to replace instances of Access ID
if(line.Contains(Variable) == true)
{
fileTexts[counter] = fileTexts[counter].Replace(Variable, textBox2.Text);
}
}
counter++;
}
//check if file exists in the backup folder
if(File.Exists("Tests\\Text\\file name "+ textBox1.Text +".sql") == true)
{
MessageBox.Show("This file already exist in the backup folder");
return false;
}
else
{
//update the file
File.WriteAllLines(destFileName, fileTexts);
File.Move(destFileName, "Tests\\Text\\file name"+ textBox1.Text +".sql");
MessageBox.Show("Completed");
return true;
}
}
答案 0 :(得分:1)
您的问题似乎是将文件名变量从循环传递给方法。
为了做你想做的事,请在方法中添加一个参数:
private bool ModifySQLFile(string filename)
{
string[] fileTexts = File.ReadAllLines(filename);
// ...
}
然后使用此参数调用方法:
for (int i = 0; i<fileArray.Length; i++)
{
ModifySQLFile(fileArray[i]);
}
但总的来说,你真的不想像你那样将正式语言视为明文。像那样打破SQL非常容易。如果用户想要替换文本&#34;插入&#34;或用&#34; foo&#39; bar&#34;?
取代某些内容该怎么办?答案 1 :(得分:1)
首先,实施一个(file
)修改:
private bool modifySQLFile(String file) {
// given source file, let´s elaborate target file name
String targetFile = Path.Combine(
Path.GetDirectoryName(file),
String.Format("{0}{1}.sql",
Path.GetFileNameWithoutExtension(file),
textBox1.Text));
// In case you want a back up
//TODO: given source file name, elaborate back up file name
//String backUpFile = Path.Combine(...);
// Check (validate) before processing: do not override existing files
if (File.Exists(targetFile))
return false;
//TODO: what if back up file exists? Should we override it? skip?
// if line doesn't start with SQL commentary --
// and contains a variable, substitute the variable with its value
var target = File
.ReadLines(file)
.Select(line => (!line.StartsWith("--") && line.Contains(Variable))
? line.Replace(Variable, textBox2.Text)
: line);
// write modified above lines into file
File.WriteAllLines(targetFile, target);
// In case you want a back up
// Move file to backup
//File.Move(file, backUpFile);
return true;
}
然后在循环中调用它:
// enumerate all the text files in the directory
var files = Directory
.EnumerateFiles("@"Tests\Text", "*.txt");
//TODO: you may want filter out some files with .Where
//.Where(file => ...);
// update all the files found above
foreach (var file in files) {
if (!modifySQLFile(file))
MessageBox.Show(String.Format("{0} already exist in the backup folder", file));
}
请不要这样做:
@"Tests\Text\"
modifySQLFile
是什么
MessageBox.Show(...)
和逻辑:modifySQLFile
返回true
或false
,并且可以显示留言框的来电者。Directory.GetFiles
,File.ReadAllLines
)答案 2 :(得分:-1)
如果您想并行编辑文件。使用线程,您可以并行化工作。
for (int i = 0; i < fileArray.Length; i++)
new Thread(UpdateFileThread).Start(fileArray[i]);
private void UpdateFileThread(object path)
{
string filePath = (string)path;
//ToDo: Edit file
}
在您的情况下,您将创建10个线程。该解决方案可行,但如果您必须处理10个以上的文件,这是一个糟糕的模式。
答案 3 :(得分:-2)
下面我发布了实时代码,我使用了项目
protected void btnSqlfinder_Click(object sender, EventArgs e)
{
//Defining the path of directory where all files saved
string filepath = @ "D:\TPMS\App_Code\";
//get the all file names inside the directory
string[] files = Directory.GetFiles(filepath);
//loop through the files to search file one by one
for (int i = 0; i < files.Length; i++)
{
string sourcefilename = files[i];
StreamReader sr = File.OpenText(sourcefilename);
string sourceline = "";
int lineno = 0;
while ((sourceline = sr.ReadLine()) != null)
{
lineno++;
//defining the Keyword for search
if (sourceline.Contains("from"))
{
//append the result to multiline text box
TxtResult.Text += sourcefilename + lineno.ToString() + sourceline + System.Environment.NewLine;
}
if (sourceline.Contains("into"))
{
TxtResult.Text += sourcefilename + lineno.ToString() + sourceline + System.Environment.NewLine;
}
if (sourceline.Contains("set"))
{
TxtResult.Text += sourcefilename + lineno.ToString() + sourceline + System.Environment.NewLine;
}
if (sourceline.Contains("delete"))
{
TxtResult.Text += sourcefilename + lineno.ToString() + sourceline + System.Environment.NewLine;
}
}
}
}
此代码将获取给定目录中的多个文件,并在单独的文本中按关键字显示行。
但你可以根据自己的要求轻松改变,请告诉我你的想法。
由于