c# - 从控制台中删除特殊字符以加载 txt 文件

标签 c# console special-characters

所以我的最后一个问题不清楚,所以这是我的第二次尝试。

当我将我的 txt 文件拖放到控制台中时,我得到如下路径:

"C:\Dokumente und Einstellungen\Bektas\Desktop\test\text1.txt"

如何自动删除 " 字符?

在将我的路径保存到字符串中之前,我必须手动删除它...

这是我的代码:

    static void Main(string[] args)
    {
        String pfad;
        String pfad2;
        String speichern = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\ausgabe.txt";

        try
        {
            Console.WriteLine("Pfad eingeben: ");
            pfad = Console.ReadLine();

            Console.WriteLine("Pfad eingeben: ");
            pfad2 = Console.ReadLine();
            // Input
            List<String> data = File.ReadAllLines(pfad)
                .Concat(File.ReadAllLines(pfad2))
                .Distinct().ToList();

            // Processing
            data.Sort();

            // Output
            Console.WriteLine("Duplikate entfernt & sortiert:");
            data.ForEach(Console.WriteLine);
            File.WriteAllLines(speichern, data.ToArray());

        }
        catch (Exception e)
        {
            Console.WriteLine("Die Anwendung schlug fehl: {0}\t" + e.ToString());
        }

        Console.ReadKey();

    }
}

最佳答案

您可以通过执行以下操作自动删除 " 字符:

Console.WriteLine("Pfad eingeben: ");
pfad = Console.ReadLine();
if (pfad.StartsWith("\"") && pfad.EndsWith("\"")) {
    pfad = pfad.Substring(1, pfad.Length - 2);
}

此外,由于您使用 pfadpfad2 执行了两次,您应该将此代码提取到一个函数中以减少代码重复:

private static string RemoveQuotes(string input) {
    if (input.StartsWith("\"") && input.EndsWith("\"")) {
        return input.Substring(1, input.Length - 2);
    } else {
        return input;
    }
}

public static void Main(string[] args) {

  // ...

  Console.WriteLine("Pfad eingeben: ");
  pfad = RemoveQuotes(Console.ReadLine());

  Console.WriteLine("Pfad eingeben: ");
  pfad2 = RemoveQuotes(Console.ReadLine());      

  // ...

关于c# - 从控制台中删除特殊字符以加载 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8899681/

相关文章:

batch-file - 如何确定 *.bat 文件是从控制台运行还是单独运行?

java - iText PDF 中的 Unicode 字符

php - 排序规则 "latin1_swedish_ci"中数据库的回显导致网页上出现问号符号

C# Entity Framework 查询结果不正确

c# - 如何拥有 IEnumerable<T>.ToObservableCollection()?

c# - 删除验证消息名称中的集合索引

javascript - 验证特殊字符 JavaScript

c# - 被 OverflowException 击中

c# - "return"C#的返回类型是什么

c# - 如何在批处理文件中获取控制台应用程序的返回值?