我希望有人可以帮助我。我是c#的初学者和一般的编程,我正在尝试完成这个程序。基本上它在XML文件中查找,捕获特定标记的所有出现,并且应该写入文件名以及这两个标记的任何实例之间的任何内容。到目前为止,我已经尝试过TextWriter,StreamWriter,FileStream和其他一些东西,没有做任何我想做的事情。我意识到这可能是一个愚蠢的问题,但我是一个超级菜鸟,需要帮助我的具体情况。我的代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var files = from file in Directory.GetFiles("W:\\SRC\\hDefMl\\1.0\\Instrument_Files")
orderby file
ascending
select file;
StringBuilder sb_report = new StringBuilder();
string delimiter = ",";
sb_report.AppendLine(string.Join(delimiter, "Module", "Generator(s)"));
foreach (var file in files)
{
string filename = Path.GetFileNameWithoutExtension(file);
Console.WriteLine("The HDefML file for {0} contains these EEPROM Generators:", filename);
XDocument hdefml = XDocument.Load(file);
var GeneratorNames = from b in hdefml.Descendants("Generators")
select new
{
name = (string)b.Element("GeneratorName")
};
string description;
foreach (var generator in GeneratorNames)
{
Console.WriteLine(" GeneratorName is: {0}", generator.name);
sb_report.AppendLine(string.Join(delimiter, filename,
generator.name));
}
}
}
答案 0 :(得分:1)
如果您使用字符串生成器构建的字符串格式正确,您应该可以执行此类操作。
static void WriteToCSV(string str, string path)
{
using (Stream stream = File.Create(path))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(str);
}
}
答案 1 :(得分:0)
try{
FileStream FS;
StreamWriter SW;
using (FS = new FileStream("HardCodedFileName.csv", FileMode.Append))
{
using (SW = new StreamWriter(FS))
{
foreach (var generator in GeneratorNames)
{
SW.WriteLine(string.Join(delimiter, filename,
generator.name));
}
}
}
}
catch (Exception e){
Console.Writeline(e.ToString());
}