我有许多文本文件都遵循相同的内容格式:
"Title section","Version of the app"
10
"<thing 1>","<thing 2>","<thing 3>","<thing 4>","<thing 5>","<thing 6>","<thing 7>","<thing 8>","<thing 9>","<thing 10>"
'Where:
' first line never changes, it always contains exactly these 2 items
' second line is a count of how many "line 3s" there are
' line 3 contains a command to execute and (up to) 9 parameters
' - there will always be 10 qoute-delimited entries, even if some are blank
' - there can be N number of entries (in this example, there will be 10 commands to read)
我正在使用StreamReader阅读每个文本文件,并希望在自己的类中设置每个文件。
public class MyTextFile{
public string[] HeaderLine { get; set; }
public int ItemCount { get; set; }
List<MyCommandLine> Commands { get; set;}
}
public class MyCommandLine{
public string[] MyCommand { get; set; }
}
private void btnGetMyFilesiles_Click(object sender, EventArgs e){
DirectoryInfo myFolder = new DirectoryInfo(@"C:\FileSpot");
FileInfo[] myfiles = myfolder.GetFiles("*.ses");
string line = "";
foreach(FileInfo file in Files ){
str = str + ", " + file.Name;
// Read the file and display it line by line.
System.IO.StreamReader readingFile = new System.IO.StreamReader(file.Name);
MyTextFile myFileObject = new MyTextFile()
while ((line = readingFile.ReadLine()) != null){
' create the new MyTextFile here
}
file.Close();
}
}
}
目标是确定所调用的实际命令是什么(&#34;&#34;),如果任何其余参数指向预先存在的文件,则确定该文件是否存在。我的问题是,我无法弄清楚如何阅读N号&#34;第3行&#34;到他们自己的对象并将这些对象附加到MyTextFile对象。我99%肯定我已逐渐误入歧途阅读每个文件,但我不知道如何摆脱它。
答案 0 :(得分:1)
因此,针对将N个第3行项目纳入您的课程的具体问题,您可以执行类似的操作(显然您可以进行一些更改,因此它更适合您的应用程序)。
public class MyTextFile
{
public List<Array> Commands = new List<Array>();
public void EnumerateCommands()
{
for (int i = 0; i < Commands.Count; i++)
{
foreach (var c in Commands[i])
Console.Write(c + " ");
Console.WriteLine();
}
}
}
class Program
{
static void Main(string[] args)
{
string line = "";
int count = 0;
MyTextFile tf = new MyTextFile();
using (StreamReader sr = new StreamReader(@"path"))
{
while ((line = sr.ReadLine()) != null)
{
count += 1;
if (count >= 3)
{
object[] Arguments = line.Split(',');
tf.Commands.Add(Arguments);
}
}
}
tf.EnumerateCommands();
Console.ReadLine();
}
}
至少现在你的“MyTextFile”中有一个命令列表。你可以枚举并做一些事情的课程。
**我添加了EnumerateCommands方法,以便您实际上可以看到列表正在存储订单项。代码应该在控制台应用程序中运行,并使用适当的&#39;使用&#39;语句。
希望这有帮助。
答案 1 :(得分:0)
如果所有内容都以逗号,
分隔,您可以执行以下操作:
int length = Convert.ToInt32 (reader.ReadLine ());
string line = reader.ReadLine ();
IEnumerable <string> things = line.Split (',').Select (thing => thing. Replace ('\"'', string.Empty).Take(length);
Take
表示从该行中获取了多少things
。