所以我试图将变量存储到文本文件中,以便我的程序以后可以调用它们,但是我需要这些文件具有设置的名称,并且当我尝试使其永远无法正常工作时。
我尝试过在foreach循环中使用foreach循环,我尝试了很多事情,但是所有这些事情都只是弄乱了变量数据
string[] lines = { name, FirstBlock, MonIstem, WedIstem, ThridBlock, FourthBlock, "Design Time", SixthBlock, TueIstem, ThurIstem, EighthBlock, NinthBlock, "Design Time", FriIstem };
string[] names = { "name", "FirstBlock", "MonIstem", "WedIstem", "ThirdBlock", "FourthBlock", "Design Time", "SixthBlock", "TueIstem", "ThurIstem", "EightBlock", "NinthBlock", "Design Time", "FriIstem", };
foreach (string TXTname in names)
{
Console.WriteLine($"Saving {TXTname}");
}
foreach (string line in lines)
{
string getNameOfVar = nameof(line);
using (FileStream bs = File.OpenWrite($@"C:\Users\gn193755\Documents\{TXTname}.txt"))
{
byte[] thing = new UTF8Encoding(true).GetBytes(line);
bs.Write(thing, 0, thing.Length);
}
}
没有错误消息,但是当我打开文本文件时,要么只有一个文本文件,要么它们上都带有相同的单词,或者它们只是乱码文本,所以我一直希望使用正确的文件名。正确的文字。
答案 0 :(得分:1)
我太笨了,我做了更多研究,找到了.zip文件。
var lines = new [] { name, FirstBlock, MonIstem, WedIstem, ThridBlock, FourthBlock, "Design Time", SixthBlock, TueIstem, ThurIstem, EighthBlock, NinthBlock, "Design Time", FriIstem };
var names = new [] { "name", "FirstBlock", "MonIstem", "WedIstem", "ThirdBlock", "FourthBlock", "Design Time", "SixthBlock", "TueIstem", "ThurIstem", "EightBlock", "NinthBlock", "Design Time", "FriIstem", };
var linesAndnames = lines.Zip(names, (l, n) => new { Line = l, Name = n });
foreach (var ln in linesAndnames)
{
var path = $@"C:\Users\gn193755\Documents\{ln.Name}.txt";
File.WriteAllText(path, ln.Line);
}
}
答案 1 :(得分:0)
string getNameOfVar = nameof(line);
var path = $@"C:\Users\gn193755\Documents\{TXTname}.txt");
File.WriteAllText(path, line);
尝试此操作,以确保正确写入行字符串:
var path = $@"C:\Users\gn193755\Documents\output.txt");
File.AppendAllText(path, line);
答案 2 :(得分:0)
从代码中可以看出,foreach循环是独立的。
string[] lines = { name, FirstBlock, MonIstem, WedIstem, ThridBlock, FourthBlock, "Design Time", SixthBlock, TueIstem, ThurIstem, EighthBlock, NinthBlock, "Design Time", FriIstem };
string[] names = { "name", "FirstBlock", "MonIstem", "WedIstem", "ThirdBlock", "FourthBlock", "Design Time", "SixthBlock", "TueIstem", "ThurIstem", "EightBlock", "NinthBlock", "Design Time", "FriIstem", };
foreach (string TXTname in names)
{
Console.WriteLine($"Saving {TXTname}");
foreach (string line in lines)
{
string getNameOfVar = nameof(line);
using (FileStream bs = File.OpenWrite($@"C:\Users\gn193755\Documents\{TXTname}.txt"))
{
byte[] thing = new UTF8Encoding(true).GetBytes(line);
bs.Write(thing, 0, thing.Length);
}
}
}
尝试使用上面的代码