0

I'm tring to export a sql database into .bak file and I've got the following scenario when I try to make the export using a long file path (greater than 260 characters). Also I'm using a save dialog to allow the user to specify the path where the bak file shall be stored, and when the given path exceeds 260 characters the save button of the save dialog doesn't make anything. Is there any way to handle long paths inside my c# application. I've tried to prefix the file path with "\?" like

  SaveFileDialog dialog = CreateExportSaveFileDialog();

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string pathFileName = @"\\?\" + dialog.FileName;

                
                ExportConfigurationDatabase(databaseName, pathFileName);
            }

and the sql command which performs the bak export :

string sqlDynamicQuery = "DECLARE @sql nvarchar (max) = (" +
                                     "SELECT " +
                                     "'BACKUP DATABASE '" +
                                     "+ QUOTENAME(name) " +
                                     "+ ' TO DISK=@outputfile WITH FORMAT,COPY_ONLY,INIT, NAME = @backup_set_name_var, SKIP' " +
                                     "FROM sys.databases " +
                                     "WHERE name = @database); "+
                                     "EXEC sp_executesql " +
                                     "@sql, " +
                                     "N'@backup_set_name_var nvarchar(128), @outputfile nvarchar(MAX)', "+
                                     "@backup_set_name_var = @backup_set_name_var, "+
                                     "@outputfile = @outputfile; ";
                                     

            using (SqlCommand sqlCmd = new SqlCommand(sqlDynamicQuery, _sqlConnection))
            {
                sqlCmd.Parameters.Add("@database", SqlDbType.NVarChar, 128).Value = databaseName;
                sqlCmd.Parameters.Add("@backup_set_name_var", SqlDbType.NVarChar, 128).Value = databaseName + " -Full Database Backup";
                sqlCmd.Parameters.Add("@outputfile", SqlDbType.NVarChar, -1).Value = outputFile;

                sqlCmd.ExecuteNonQuery();
            }

EDIT: As suggested I've tried to modify the App.config like this

<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/></startup>
  <runtime><AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false"/></runtime>

but then in the savedialog when I tried to introduce a path longer than 260 characters , dialog.FileName becomes "" and "The given path's format is not supported." is throwned. . Any respons will be highly appreciated.

  • https://stackoverflow.com/questions/5188527/how-to-deal-with-files-with-a-name-longer-than-259-characters – urlreader Jun 09 '21 at 17:16

0 Answers0