如何替换文件中保存的字符串

时间:2017-09-10 18:00:06

标签: c# file-io

我正在编写程序来查找具有pi数字的十六进制表示的md5哈希。我在保存计算时遇到了问题。看起来程序不能正确保存字符串。它构成一个长字符串而不是替换旧字符串。我该如何解决这个问题?

        public static string get_last_string()
        {
            string text;
            string text2="";
            int i= 0;
            string path = "C:\\Users\\uname\\Desktop";
            var fileStream = new FileStream(@path + "\\last.txt", FileMode.Open, FileAccess.Read);
            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
            {
                text = streamReader.ReadToEnd();
            }
            i=0;

            while (i < text.Length && text[i] != ' ')
            {
                text2 += text[i];
                ++i;
            }
            return text2;
        }

        public static void Main(string[] args)
        {

            string path = @"C:\Users\Uname\Desktop\test.txt";
            string a = get_last_string();
            Console.WriteLine("Let us continue from the string " + a);
            Console.WriteLine("Ctrl+C stops the computing and saves the results to the file last.txt");
            do
            {
                while (!Console.KeyAvailable)
                {
                    //                   Console.WriteLine("md5("+a+")="+CalculateMD5Hash(a));

                    if (CommonPrefix(CalculateMD5Hash(a), "314159265353") >= 11)
                    {

                        Console.WriteLine(a + " " + CalculateMD5Hash(a));
                        File.WriteAllText(path, a + " " + CalculateMD5Hash(a));
                    }

                    a = Next(a);
                }

            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
            File.AppendAllText(@path + "\\last.txt", a);
        }

1 个答案:

答案 0 :(得分:0)

您有File.WriteAllText(...,之后您有File.AppendAllText(... 我很害羞你正在写两次文件。