简体   繁体   English

c#-无法备份mysql数据库,错误为“不支持给定路径的格式。”

[英]c# - unable to backup mysql database with error “The given path's format is not supported.”

private void Backup()
    {
        string x = txtb.Text; 
        string date = DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss");
        string file = x + date + "database backup.sql";
        string conn = "server = localhost; user id = root; password =; database = sais_db;";

        try
        {
            MySqlBackup mb = new MySqlBackup(conn);
            mb.Export(file);
            MessageBox.Show("Database Backup Success!");
        }

        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Help please, when I run my program, I get a NotSupportedException error. 请帮忙,当我运行程序时,出现NotSupportedException错误。 How do I fix it? 我如何解决它?

PS txtb.Text contains directory path like this C:\\Users\\user\\Desktop PS txtb.Text包含目录路径,例如C:\\ Users \\ user \\ Desktop

Your DateTime format includes colons. 您的DateTime格式包括冒号。 Those are not allowed in a file or pathname except for delimiting the drive letter from the path. 在文件或路径名中不允许使用这些字符,除非从路径中分隔驱动器号。

You can easily fix that by changing the format string of your DateTime.Now call: 您可以通过更改DateTime.Now调用的格式字符串轻松解决此问题:

string x = txtb.Text; 
string date = DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss");
string file = x + date + "database backup.sql";

When you run this you'll get (assumimg txtb.Text contains foo ) in file 运行此文件时,您将在file获取(assumimg txtb.Text包含foo

foo09-24-2016 14-20-59database backup.sql foo09-24-2016 14-20-59数据库backup.sql

You can also consider to do that in one go: 您也可以考虑一口气做到这一点:

string file = String.Format(
    "{0}{1:MM-dd-yyyy HH-mm-ss}database backup.sql", 
    txtb.Text,
    DateTime.Now);

If you allow your users to provide (part of) a filename consider checking for invalid characters. 如果允许用户提供文件名(的一部分),请考虑检查无效字符。 The Path class in the System.IO namespace has a nice helper for that GetInvalidFileNameChars . System.IO命名空间中的Path类为该GetInvalidFileNameChars提供了很好的帮助。

if (file.IndexOfAny(Path.GetInvalidFileNameChars()) > -1) 
{
    // show an error
    MessageBox.Show("invalid characters in file");
   return;
}

There is a similar method for InvalidPathChars InvalidPathChars有类似的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM