0

所以我正在编写一个 C# 程序,它将几个文本文件组合成一个并将它们保存为一个组合文本文件。One issue I am having, I have a textfield which selects the intended folder the save the compiled reciept, however when selecting the desired folder, it generates a file name to the text box, the filename follwing the final / must be erased every time for保存功能正常工作。我想知道,如何删除文件目录中最后一个 / 之前最后一个字母之后的所有文本?

这是代码:

private void RecieptDisplayed_TextChanged(object sender, EventArgs e)
{
    try
    {
        string[] fileAry = Directory.GetFiles(RecieptSelect.Text);

        string input = RecieptSelect.Text;
        int index = input.LastIndexOf("/");
        if (index >= 0)
            input = input.Substring(0, index);

        MessageBox.Show("Reciepts being processed : " + index);

        using (TextWriter tw = new StreamWriter(savefileas.Text + "RecieptsCombined.txt", true))
        {
            foreach (string filePath in fileAry)
            {
                using (TextReader tr = new StreamReader(filePath))
                {
                    tw.WriteLine("Reciept for: " + " " + filePath + tr.ReadToEnd()) ;
                    tr.Close();
                    tr.Dispose();
                }
                MessageBox.Show("File Processed : " + filePath);
            }

            tw.Close();
            tw.Dispose();
        }
    }
4

3 回答 3

1

你有一个字符串

var fullpath = @"C:\temp\myfile.txt";

您可以使用:

var dir = Path.GetDirectoryName(fullpath);

要得到

c:\temp

请注意,如果路径以斜杠结尾,则不会在“向上目录”之前将其删除,因此c:\temp\变为c:\temp. 尽量让你的路径没有斜杠

在操作作为路径的字符串时,请尝试始终使用 Path 类。它有很多有用的方法(这不是一个详尽的列表,而是我最常用的方法),例如:

GetFileName
GetFileNameWithoutExtension
GetExtension 
ChangeExtension
Combine

最后一个构建路径,例如:

Path.Combine("c:", "temp", "myfile.txt");

它知道它运行的不同操作系统并适当地构建路径 - 如果您在 Linux 上使用它使用的 net core,"/"而不是"\"例如。完整的文档在这里

于 2021-10-26T05:21:27.647 回答
0

您正在从给定路径中查找目录名称,您可以使用现有函数来获取目录名称,Path.GetDirectoryName()

using System.IO;
...

//Get the directory name
var directoryName = Path.GetDirectoryName(savefileas.Text);

using (TextWriter tw = new StreamWriter(Path.Combine(directoryName, "RecieptsCombined.txt"), true))

{
      foreach (string filePath in fileAry)
      {
            using (TextReader tr = new StreamReader(filePath))
            {
                tw.WriteLine("Reciept for: " + " " + filePath + tr.ReadToEnd()) ;
                tr.Close();
                tr.Dispose();
            }
            MessageBox.Show("File Processed : " + filePath);
      }

      tw.Close();
      tw.Dispose();
}
于 2021-10-26T05:19:55.550 回答
0

从字符串构造一个FileInfo 对象,然后使用DirectoryNameDirectory

此外,不要连接字符串来获取文件名,而是使用Path.Combine

于 2021-10-26T05:20:18.003 回答