我有一个读取的文本文件:

INSERT INTO `shops` VALUES ('', '3', '1000000', '0');
INSERT INTO `shops` VALUES ('', '3', '1000010', '0');
INSERT INTO `shops` VALUES ('', '3', '1000020', '0');
INSERT INTO `shops` VALUES ('', '3', '1000030', '0');
INSERT INTO `shops` VALUES ('', '3', '1001000', '0');

请注意,对于每一行,第一个键是“”。对于每一行,我想找到'',并用数字替换(以1开头),然后将其添加到下一行,因此将其添加1,如下所示:
INSERT INTO `shops` VALUES ('1', '3', '1000000', '0');
INSERT INTO `shops` VALUES ('2', '3', '1000010', '0');
INSERT INTO `shops` VALUES ('3', '3', '1000020', '0');
INSERT INTO `shops` VALUES ('4', '3', '1000030', '0');
INSERT INTO `shops` VALUES ('5', '3', '1001000', '0');

我已经尝试了几个小时,但是失败了。

这就是我一直在想的(我知道这很不正确,但是我在C#中并不那么精明,所以也许你们中的一个可以帮助我提出正确的代码):
string text = File.ReadAllText("C:\\Users\\Donavon\\Desktop\\old.sql");

int i = 0;
text = text.Replace("('',", "('" + i + "',");
i++;
File.WriteAllText("C:\\Users\\Donavon\\Desktop\\new.sql", text);

谢谢您的帮助,不胜感激

最佳答案

您可以逐行阅读以下行:

string text = "";
using (StreamReader sr = new StreamReader("C:\\Users\\Donavon\\Desktop\\old.sql"))
{
    int i = 0;
    do
    {
        i++;
        string line = sr.ReadLine();
        if (line != "")
        {
            line = line.Replace("('',", "('" + i + "',");
            text = text + line + Environment.NewLine;
        }
    } while (sr.EndOfStream == false);
}
File.WriteAllText("C:\\Users\\Donavon\\Desktop\\new.sql", text);

关于c# - 如何在文本文件中逐行读取和替换字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32274427/

10-11 06:48