如何从字符串中删除最后一个字符

Posted

技术标签:

【中文标题】如何从字符串中删除最后一个字符【英文标题】:How to remove last characters from a string 【发布时间】:2021-12-11 12:17:56 【问题描述】:

所以我正在编写一个 C# 程序,它将几个文本文件组合成一个并将它们保存为一个组合文本文件。我拥有的一个问题,我有一个文本字段,它选择了保存编译的接收的预期文件夹,但是在选择所需的文件夹时,它会在文本框中生成文件名,每次都会删除最终/必须删除的文件名。保存功能正常工作。我想知道,如何删除文件目录中最后一个 / 之前最后一个字母之后的所有文本?

代码如下:

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();
        
    

【问题讨论】:

【参考方案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,它使用 "/" 而不是 "\"。 full docs here

【讨论】:

试试看,谢谢!【参考方案2】:

构造一个FileInfo object from the string,然后使用DirectoryName 或Directory。

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

【讨论】:

【参考方案3】:

您正在从给定路径中查找目录名称,您可以使用现有函数来获取目录名称,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();

【讨论】:

@user17019895,如果它适合您,请通过绿色勾号接受答案

以上是关于如何从字符串中删除最后一个字符的主要内容,如果未能解决你的问题,请参考以下文章

如何从 python 中的字符串中只删除最后一个括号?

如何删除最后一个字符(从数组创建字符串时的逗号)? [复制]

从字符串中删除最后一个字符

从 C++ 字符串中删除最后一个字符

从字符串中删除最后一个字符。斯威夫特语言

如何删除 ksh 中字符串变量的最后一个字符?