【问题标题】:Use the output(StreamReader) line as file name(rename)使用输出(StreamReader)行作为文件名(重命名)
【发布时间】:2014-01-11 03:49:28
【问题描述】:

我正在尝试使用输出(“行”)作为新文件名(文件已经存在,只需重命名)。 例如"A,tampqer,n:.jpg" 但它看起来像: 例如行="A\tampqer\tn:\t\t"

我得到一个错误:文件名的非法字符。

            int counter = 0;

        string line;

        // Read the file and display it line by line.


        StreamReader file = new StreamReader(@"C:\\german-czech.txt");
        while ((line = file.ReadLine()) != null)
        {
            //replace /t doesnt work
            for (int i = 0; i < line.Length; i++)
            {
                if (line[i] == '\t')
                {
                    line.Replace(line[i], ',');
                }
            }

            //Console.WriteLine(string.Format(line, @"\\t").ToString());
            Console.WriteLine( line);
            counter++;

            if (counter == 100)
                break;

        }
        file.Close();

猜猜“行”的内容仍然是一样的......谁能帮我解决这个小问题? 我还尝试了什么? line.Replace(System.Environment.NewLine, ","); 字符串.空... "\n" 最好的问候

【问题讨论】:

  • 如果A,tampqer,n:.jpgA\tampqer\tn:\t\t 中的任何一个是文件名,您应该知道冒号':' 是Windows 上文件名的非法字符。此外,虽然我相信 @"C:\\german-czech.txt" 会起作用,但您可能想要使用 @"C:\german-czech.txt""C:\\german-czech.txt"

标签: c# file replace rename streamreader


【解决方案1】:

你需要

line = line.Replace(line[i], ',');

它不会就地改变它。它返回一个 new 字符串。

你也不需要一根一根地横穿琴弦。 Replace 将替换字符串中的每个出现。所以代替你的:

    //replace /t doesnt work
    for (int i = 0; i < line.Length; i++)
    {
        if (line[i] == '\t')
        {
            line.Replace(line[i], ',');
        }
    }

只要有:

line = line.Replace("\t", ',');

(这是在更正您的代码。但我认为 mrzli 在他的评论中得到了真正的错误。)

【讨论】:

  • "不支持给定路径的格式。"对于该语句“File.Move(f.FullName, Path.Combine(f.DirectoryName,line.ToString() + f.Extension));” - 但只有当我将“line.toString()”与其他名称一起使用时才有效。“line”现在看起来像“A,ampqer,n:,”...
  • 好的,你们都说得对。我也替换了“:”。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 2020-12-18
  • 2017-12-12
  • 1970-01-01
相关资源
最近更新 更多