如何使用C#修改文本文件中的特定行?

时间:2011-08-21 09:25:46

标签: c# text-files

我的srt文件包含这样的电影字幕:

1
00:00:00,082 - > 00:00:04352
bbb bbb bb
bbb bb

2
00:00:08,486 - > 00:00:12662个
bbb bbb bbb

3
00:00:12,824 - > 00:00:14963个
BBB
bbbb bb

我想将常量值添加到分钟(因此稍后会显示字幕)。我怎么能这样做?

我已经有了这段代码:

class MainClass
{

    public static void Main (string[] args)
    {
        StringBuilder sb = new StringBuilder();

        using(FileStream fs = new FileStream(@"sb.srt",FileMode.Open,FileAccess.ReadWrite))
        {
            using(StreamReader sr = new StreamReader(fs))
            {
                while( sr.Read()!=-1 )
                {
                    sb.AppendLine(sr.ReadLine());
                }
            }
        }
    }
}

3 个答案:

答案 0 :(得分:4)

这是一个完整的程序。只需将时间长度更改为您要添加的数量

const string format = @"hh\:mm\:ss\,fff";
        static void Main(string[] args)
        {
            string input = File.ReadAllText("sb.srt");
            Regex r = new Regex(@"(\d\d):(\d\d):(\d\d),(\d\d\d)");
            input = r.Replace(input, m=> AddTime(m));
            File.WriteAllText("sb.srt", input);
        }

        private static string AddTime(Match m)
        {
            TimeSpan t = TimeSpan.ParseExact(m.Value, format, CultureInfo.InvariantCulture);
            t += new TimeSpan(0, 1, 0);
            return t.ToString(format);
        }

答案 1 :(得分:2)

我会使用匹配行的正则表达式

00:00:08,486 --> 00:00:12,662

然后将Regex.Replace与自定义MatchEvaluator一起使用,它会解析时间码,添加时差并将新时间码作为字符串返回。

时间码的简单正则表达式是

"^\s*(\d\d):(\d\d):(\d\d),(\d\d\d)\s*-->\s*(\d\d):(\d\d):(\d\d),(\d\d\d)\s*$"

对于评估者,您可以从匹配的相应字段构造两个TimeSpan值,添加时差并使用String.Format构造结果字符串。

这样,你可以使用File.ReadAllText将整个文本文件加载到一个字符串中,处理它并使用File.WriteAllText将其写回来,这使得核心例程成为一个三线程:)

PS:不要忘记使用RegexOptions.Multiline选项,以使"^""$"正常工作。

答案 2 :(得分:1)

    private static string ProcessLine(string line, int seconds)
    {
        var regex = new Regex(@"^(\d\d:\d\d:\d\d,\d\d\d) --> (\d\d:\d\d:\d\d,\d\d\d)");

        var match = regex.Match(line);

        if (match.Success)
        {
            var from = AddSeconds(match.Groups[1].ToString(), seconds);
            var to = AddSeconds(match.Groups[2].ToString(), seconds);
            return string.Format("{0} --> {1}", from, to);
        }
        else
        {
            return line;
        }
    }

    private static string AddSeconds(string timestamp, int seconds)
    {
        var datetime = DateTime.ParseExact(timestamp, "HH:mm:ss,fff", CultureInfo.InvariantCulture);
        return datetime.AddSeconds(seconds).ToString("HH:mm:ss,fff"); 
    }

sb.AppendLine(sr.ReadLine());替换为原始代码中的sb.AppendLine(ProcessLine(sr.ReadLine(), 60));