Нежелательные escape-символы в строке

Содержимое файла App.Config:

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>

    <appSettings>
        <add key="ConnectionString"
             value="Server=ADVDSQLMGA;User ID=ImporterApp;Password=!mp0rt3rApp;Database=id0405Moxy52"
             />


        <add key="DTS_PackageName"
            value="BlockImportNEW"/>
        <add key="DTS_PackagePathAndFileName"
            value="\\computername\foldername\folder1\folder2\folder3\filename.dts"/>
        <add key="DTS_PackageGUID"
            value="{C22A80D9-7613-43AF-939C-3C04AD7D848A}"/>
        <add key="DTS_ImportSourcePath"
            value="C:\foldername"/>
        <add key="DTS_ImportFileConnection"
             value="'filename.txt';'';'0'"/>
        <add key="DTS_ImportFileName"
             value="filename.txt"/>
        <add key="DTS_ImportWorkingPath"
             value="\\computername\foldername\folder1\folder2"/>
        <add key="DTS_ImportWorkingPathAndFileName"
             value="\\computername\foldername\folder1\folder2\filename.txt"/>
        <add key="DTS_DestinationServerName"
             value="computername"/>
        <add key="DTS_DestinationDatabase"
             value="databasename"/>
        <add key="DTS_DestinationTable"
             value="databasename.dbo.tablename"/>
        <add key="DTS_DestinationUserName"
             value="username"/>
        <add key="DTS_DestinationPassword"
             value="password"/>
    </appSettings>


</configuration>

Код:

            string DTS_PackageName = ConfigurationSettings.AppSettings["DTS_PackageName"];
            string DTS_PackagePathAndFileName = ConfigurationSettings.AppSettings["DTS_PackagePathAndFileName"];
            string DTS_PackageGUID = ConfigurationSettings.AppSettings["DTS_PackageGUID"];
            string DTS_ImportSourcePath = ConfigurationSettings.AppSettings["DTS_ImportSourcePath"];
            string DTS_ImportFileConnection = ConfigurationSettings.AppSettings["DTS_ImportFileConnection"];
            string DTS_ImportFileName = ConfigurationSettings.AppSettings["DTS_ImportFileName"];
            string DTS_ImportWorkingPath = ConfigurationSettings.AppSettings["DTS_ImportWorkingPath"];
            string DTS_ImportWorkingPathAndFileName = ConfigurationSettings.AppSettings["DTS_ImportWorkingPathAndFileName"];
            string DTS_DestinationServerName = ConfigurationSettings.AppSettings["DTS_DestinationServerName"];
            string DTS_DestinationDatabase = ConfigurationSettings.AppSettings["DTS_DestinationDatabase"];
            string DTS_DestinationTable = ConfigurationSettings.AppSettings["DTS_DestinationTable"];
            string DTS_DestinationUserName = ConfigurationSettings.AppSettings["DTS_DestinationUserName"];
            string DTS_DestinationPassword = ConfigurationSettings.AppSettings["DTS_DestinationPassword"];

            StringBuilder DTSArgs = new StringBuilder();

            DTSArgs.AppendFormat("/N \"{0}\" /G \"{1}\" /F \"{2}\" ",
                                        DTS_PackageName,
                                        DTS_PackageGUID,
                                        DTS_PackagePathAndFileName);            
            DTSArgs.AppendFormat(@"/A ""DestinationDatabase"":""8""=""{0}"" ", DTS_DestinationDatabase);
            DTSArgs.AppendFormat("/A \"DestinationPassword\":\"8\"=\"{0}\" ", DTS_DestinationPassword);
            DTSArgs.AppendFormat("/A \"DestinationServerName\":\"8\"=\"{0}\" ", DTS_DestinationServerName);
            DTSArgs.AppendFormat("/A \"DestinationTable\":\"8\"=\"{0}\" ", DTS_DestinationTable);
            DTSArgs.AppendFormat("/A \"DestinationUserName\":\"8\"=\"{0}\" ", DTS_DestinationUserName);
            DTSArgs.AppendFormat("/A \"ImportFileConnection\":\"8\"=\"{0}\" ", DTS_ImportFileConnection);
            DTSArgs.AppendFormat("/A \"ImportFileName\":\"8\"=\"{0}\" ", DTS_ImportFileName);
            DTSArgs.AppendFormat("/A \"ImportSourcePath\":\"8\"=\"{0}\" ", DTS_ImportSourcePath);
            DTSArgs.AppendFormat("/A \"ImportWorkingPath\":\"8\"=\"{0}\" ", DTS_ImportWorkingPath);
            DTSArgs.AppendFormat("/A \"ImportWorkingPathAndFileName\":\"8\"=\"{0}\" ", DTS_ImportWorkingPathAndFileName);
            DTSArgs.AppendFormat("/W \"0\"");

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.FileName = "dtsrun ";
//**** PROBLEM IS HERE:  The DTSArgs escpaes the double-quotes and backslashes in paths with backslashes,
//**** then the dtsrun.exe doesn’t like the arguments (see string below)
            proc.StartInfo.Arguments = DTSArgs.ToString();

            proc.Start();

            proc.WaitForExit();

Как выглядит DTSARgs:

/N "BlockImportNEW" /G "{C22A80D9-7613-43AF-939C-3C04AD7D848A}" /F "\computername\foldername\folder1\folder2\folder3\filename.dts" /A "DestinationDatabase":"8"="DBNAME " /A "DestinationPassword":"8"="password" /A "DestinationServerName":"8"="ServerName" /A "DestinationTable":"8"="dbname.dbo.tablename" /A "DestinationUserName": "8"="userName" /A "ImportFileConnection":"8"="file.txt';'';'0'" /A "ImportFileName":"8"="file.txt" /A "ImportSourcePath" :"8"="C:\BlockImport" /A "ImportWorkingPath":"8"="\computername\foldername\folder1\folder2" /A "ImportWorkingPathAndFileName":"8"="\computername\foldername\folder1\folder2 \file.txt" /W "0"

Как выглядит proc.StartInfo.Arguments:

/N \"BlockImportNEW\" /G \"{C22A80D9-7613-43AF-939C-3C04AD7D848A}\" /F \"\\computername\foldername\folder1\folder2\folder3\filename.dts\" /A \"DestinationDatabase \":\"8\"=\"ИМЯ БД\" /A \"Пароль назначения\":\"8\"=\"пароль\" /A \"Имя сервера назначения\":\"8\"=\"Имя сервера \" /A \"DestinationTable\":\"8\"=\"dbname.dbo.tablename\" /A \"DestinationUserName\":\"8\"=\"userName\" /A \"ImportFileConnection\ ":\"8\"=\"file.txt';'';'0'\" /A \"ImportFileName\":\"8\"=\"file.txt\" /A \"ImportSourcePath\ ":\"8\"=\"C:\BlockImport\" /A \"ImportWorkingPath\":\"8\"=\"\\computername\foldername\folder1\folder2\" /A \"ImportWorkingPathAndFileName\" :\"8\"=\"\\имя_компьютера\имя_папки\папка1\папка2\file.txt\" /W \"0\"

Когда выполняется proc.Start, он работает неправильно из-за всех лишних обратных слэшей. Кажется, строка построителя строк DTSArgs имеет правильный формат, но при преобразовании с помощью .ToString() и сохранении в proc.StartInfo.Arguments она получает все обратные косые черты.

Как я могу не отправлять proc.StartInfo.Arguments все эти лишние обратные косые черты?


person Adam    schedule 08.12.2009    source источник


Ответы (3)


Я сильно подозреваю, что они на самом деле не в строке. Вы случайно не пользуетесь отладчиком? Он показывает экранированную форму строки.

Запишите строку в консоль или что-то подобное, и вы увидите реальное значение.

person Jon Skeet    schedule 08.12.2009

Используете ли вы дословные строковые литералы?

Ie :

String c = @"C \B";
person C. Ross    schedule 08.12.2009
comment
Вы имеете в виду дословные строковые литералы. Просто x y является строковым литералом. - person Jon Skeet; 08.12.2009

Я обнаружил, что он отображался только с escape-символами в отладчике и непосредственном окне. При выписывании в Процесс он был фактически отформатирован исправленным. Я создал пакетный файл, который просто делал это:

echo %1
pause

Затем я вызвал пакетный файл с процессом вместо exe, который я пытался запустить. Таким образом, я мог видеть, что на самом деле было отправлено. Часть моей проблемы раньше заключалась в том, что окно cmd закрывалось слишком быстро.

Спасибо за помощь, ребята!

person Adam    schedule 08.12.2009