以txt格式编写与文件名相同的cpp文件报告

时间:2019-06-16 17:08:24

标签: c#

我正在从目录中读取文件,并读取所有文本并分别为每个文件生成报告。我想要报告名称与文件名相同。

我试图获取文件名,但是当我将其传递给报告模块时,它会给出异常错误。

 string path = "D:\\AssertCount\\";
 foreach (string sFile in Directory.EnumerateFiles(path))
 {
     assertCount=0;
     reportingCounter++;
     string[] files = Directory.GetFiles(path);
     string fileName = files[reportingCounter];
}

ReportWriting(totalWords,assertCount,fileName);

这是完整的报告编写模块

public static void ReportWriting(int totalWords, int assertCount,string fileName)
{
    StreamWriter file = new StreamWriter("D:\\AssertCount\\Reports\\"+fileName+".txt");
    file.Write("TotalWords = " + totalWords);
    file.Write("\nAasserts = " + assertCount);
    file.Write("\nOccurence of assert keyword in code is " + assertPercentage + " % ");
    file.Close();
}

发生以下异常

System.IO.IOException: 'The filename, directory name, or volume label syntax is incorrect : 'D:\AssertCount\Reports\D:\AssertCount\testData2.cpp.txt''

2 个答案:

答案 0 :(得分:1)

问题在于Directory.EnumerateFiles()和Directory.GetFiles()返回完整路径,而不是文件名。您可以尝试更换

string fileName = files[reportingCounter];

使用

string fileName = Path.GetFileNameWithoutExtension(files[reportingCounter]);

将完整路径仅转换为文件名,不带扩展名(因为稍后添加“ .txt”)。


或者,您已经使用foreach枚举了目录中的文件,那么为什么不只使用sFile?

foreach (string sFile in Directory.EnumerateFiles(path))
{
    assertCount=0;
    string fileName = Path.GetFileNameWithoutExtension(sFile);
    ReportWriting(totalWords, assertCount,fileName);
}

答案 1 :(得分:0)

您正在复制路径: 'D:\AssertCount\Reports\D:\AssertCount\testData2.cpp.txt'(应该只是'D:\AssertCount\testData2.cpp.txt'

变量fileName已经包含资源的完整路径(不仅是文件名)。因此,您只需从StreamWriter对象的创建中删除“ D:\ AssertCount \ Reports \”。代码就是这样

    public static void ReportWriting(int totalWords, int assertCount,string fileName)
    {
        StreamWriter file = new StreamWriter(fileName+".txt");
        file.Write("TotalWords = " + totalWords);
        file.Write("\nAasserts = " + assertCount);
        file.Write("\nOccurence of assert keyword in code is " + assertPercentage + " % ");
        file.Close();
    }