创建和重命名文件

时间:2016-06-02 06:42:55

标签: c# asp.net

我的文件可以在找到的备份中正确保存。我想重命名备份文件名,例如"DEPOT-Pub_Sub_Combined (wo CardHolder)" + textbox1.text + ".sql"。例如,textbox1值为1,因此它将是DEPOT-Pub_Sub_Combined (wo CardHolder) 1.sql,当我第二次运行程序时,它将创建原始备份的副本并更新该文件并将其名称保存为{ {1}}。如何才能做到这一点?我该怎么办?

textbox.text value is

2 个答案:

答案 0 :(得分:0)

我认为你应该使用“File.Move”方法。

See more at MSDN

在你的例子中,它将是:

File.Move(fileName, "DEPOT-Pub_Sub_Combined (wo CardHolder)" + textbox1.text + ".sql");

格尔茨,
Jordan Kniest

答案 1 :(得分:0)

请试试这个:

private void modifySQLFile()
{
    // make a new filename each time this method is executed
    string newFileName = @"DEPOT-Pub_Sub_Combined (wo CardHolder)" + textbox1.text + ".sql"
    // give it as parameter so that the copied file gets a new name
    CopyFile(newFileName);

    string destFileName = @"backup\DEPOT-Pub_Sub_Combined (wo CardHolder).sql" ;
    string[] fileTexts = File.ReadAllLines(@"backup\DEPOT-Pub_Sub_Combined (wo CardHolder).sql");
   int counter = 0;

    //File processing 
    foreach (string line in fileTexts)
    {
        //only process non-comments line
        if (line.StartsWith("--") == false)
        {
            //replace instances of server name
            if (line.Contains(SERVERNAME) == true)
            {
                fileTexts[counter] = fileTexts[counter].Replace(SERVERNAME, textBox1.Text);            
            }

            if (line.Contains(ACCESSID) == true)
            {
                fileTexts[counter] = fileTexts[counter].Replace(ACCESSID, textBox2.Text);
            }

            if(line.Contains(NETWORKID) == true)
            {
                fileTexts[counter] = fileTexts[counter].Replace(NETWORKID, textBox2.Text);
            }


        }
        counter++;
    }
    //update file
    File.WriteAllLines(destFileName, fileTexts);
    MessageBox.Show("Completed!");
}

// the new filename should go for the copy
private void CopyFile(string newFileName)
{

    string targetPath = @"backup";
    string destFile = Path.Combine(targetPath, newFileName);

    if(!Directory.Exists(targetPath))
    {
        Directory.CreateDirectory(targetPath);
    }

   File.Copy(fileName, destFile, true);
}