我必须在许多.txt文件中将.txt文件拆分到另一个目录中。
例如:当我到达下一个“dipendent”时,我的文本文件的第一个单词是“Dipendent”我必须剪切文件并在另一个目录中的另一个.txt文件中复制该部分文本。
所以我需要创建一个.txt文件,从第一个单词“dipendent”到下一个“dipendent”(在我的文件中大约有50个“依赖”,我必须为每个部分创建一个.txt文件文本)。
答案 0 :(得分:2)
您可以使用:
Regex.Split(myString,"Dipendent")
或
myString.Split(new [] {"Dipendent"}, StringSplitOptions.None);
您还可以查看String.Substring(Startindex, length)
编辑:应该刷新我的页面 - wudzik是对的。
答案 1 :(得分:1)
您可以使用此方法,该方法使用高效的字符串方法:
public static List<string> GetParts(string text, string token, StringComparison comparison, bool inclToken)
{
List<string> items = new List<string>();
int index = text.IndexOf(token, comparison);
while (index > -1)
{
index += token.Length;
int endIndex = text.IndexOf(token, index, comparison);
if (endIndex == -1)
{
string item = String.Format("{0}{1}", inclToken ? token : "", text.Substring(index));
items.Add(item);
break;
}
else
{
string item = String.Format("{0}{1}{0}", inclToken ? token : "", text.Substring(index, endIndex - index));
items.Add(item);
}
index = text.IndexOf(token, endIndex, comparison);
}
return items;
}
然后以这种方式使用它:
var fileText = File.ReadAllText(oldPath);
var items = GetParts(fileText, "Dipendent", StringComparison.OrdinalIgnoreCase, true);
现在您拥有所有部件,并且可以为每个部件生成新文件。
for (int i = 0; i < items.Count; i++)
{
var fileName = string.Format("Dipendent_{0}.txt", i + 1);
var fullPath = Path.Combine(destinationDirectory, fileName);
File.WriteAllText(fullPath, items[i]);
}
答案 2 :(得分:0)
不要养成让ppl编写代码的习惯,
但是,为了欢迎您加入社区:
(你应该使代码安全地打开和关闭文件。)
public void Texts(FileInfo srcFile, DirectoryInfo outDir, string splitter = "dipendent")
{
// open file reader
using (StreamReader srcRdr = new StreamReader(srcFile.FullName))
{
int outFileIdx = 1;
StreamWriter outWriter = new StreamWriter(outDir.FullName + srcFile.Name + outFileIdx + ".txt");
while (!srcRdr.EndOfStream) // read lines one by one untill ends
{
string readLine = srcRdr.ReadLine();
int indexOfSplitter = readLine.IndexOf(splitter, StringComparison.Ordinal); // find splitter
if(indexOfSplitter >= 0) // if there is a splitter
{
outWriter.WriteLine(readLine.Substring(indexOfSplitter)); // write whats before...
//outWriter.WriteLine(readLine.Substring(indexOfSplitter) + splitter.Length); // use if you want splitting text to apear in the end of the previous file
outWriter.Close(); // close the current file
outWriter.Dispose();
// update the Text to be written to exclude what's already written to the current fils
readLine = readLine.Substring(indexOfSplitter);
//readLine = readLine.Substring(indexOfSplitter + splitter.Length); // Use if you want splitting text to apear in the new file
// OPEN NEXT FILE
outFileIdx++;
outWriter = new StreamWriter(outDir.FullName + srcFile.Name + outFileIdx + ".txt");
}
outWriter.WriteLine(readLine);
}
outWriter.Close();
outWriter.Dispose();
}
}