Относительный путь для SQLite, не работающего с WIX Toolset - PullRequest
0 голосов
/ 13 сентября 2018

Я использую базу данных SQLite и создаю установщик приложения WPF с помощью WIX Toolset.Проблема в том, что приведенный ниже относительный путь работает нормально, когда я запускаю напрямую из Visual Studio, но не работает, когда я создаю установщик с WIX и после установки этой программы запуска установщика, то это приводит к фатальной ошибке для файла базы данных.В каталоге Project я создал папку Database, в которой находятся файлы базы данных, как вы можете видеть на картинке ниже:

enter image description here

После создания установщика с помощью WIX Toolset, установленные файлы какниже:

enter image description here

инвентаризация путь к файлу: enter image description here

путь dbConnectionString:

enter image description here

Я написал код для строки подключения относительного пути, как показано ниже:

Относительный путь:

  string relativePath = @"Database\inventory_control.db";
        string currentPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
        //string path = currentPath.Substring(0, currentPath.Length - 21);
        string path = Path.GetDirectoryName(currentPath);
        string absolutePath = System.IO.Path.Combine(path, relativePath);
        string dbConnectionString = string.Format("Data Source={0};Version=3;Pooling=True;Max Pool Size=100;", absolutePath);

        //string dbConnectionString = "Data Source=inventory_control.db";
        sQLiteConnection = new SQLiteConnection(dbConnectionString);

dbConnectionString дает правильный текущий путь.Приведенный выше относительный путь прекрасно работает, когда я запускаю напрямую из Visual Studio, но не работает, когда я создаю установщик с WIX.Это дает фатальную ошибку.Как решить?

WIX Файл:

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"><?define Inventory Control_TargetDir=$(var.Inventory Control.TargetDir)?>
    <Product Id="f941ba49-4369-44d4-aa0c-b77f20aa41db" Name="Inventory Control" Language="1033" Version="1.0.0.0" Manufacturer="devtros.com" UpgradeCode="ce092371-53cc-4be9-ab5d-c7a2685af970">
        <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

    <Icon Id="app_icon.ico" SourceFile="$(var.ProjectDir)app_icon.ico" />
    <Property Id="ARPPRODUCTION" Value="app_icon.ico" />

    <WixVariable Id="WixUIBannerBmp" Value="Images\background.bmp" />
    <WixVariable Id="WixUIDialogBmp" Value="Images\background.bmp" />
    <WixVariable Id="WixUILicenseRtf" Value="$(var.ProjectDir)License.rtf" />

    <Property Id="WIXUI_INSTALLDIR" Value="INSTALLFOLDER" />
    <UIRef Id="WixUI_InstallDir" />

        <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
        <MediaTemplate EmbedCab="yes" />

        <Feature Id="ProductFeature" Title="Inventory Control" Level="1">
            <ComponentGroupRef Id="ProductComponents" />
      <ComponentRef Id="ApplicationShortcut" />
      <ComponentRef Id="ApplicationShortcutDesktop" />
            <ComponentGroupRef Id="Database_files" />
        </Feature>
    </Product>

    <Fragment>
        <Directory Id="TARGETDIR" Name="SourceDir">
            <Directory Id="ProgramFilesFolder">
        <Directory Id="INSTALLFOLDER" Name="Inventory Control">
          <Directory Id="Files" Name="Files" />
          <Directory Id="Database" Name="Database" />
        </Directory>
            </Directory>
      <Directory Id="ProgramMenuFolder">
        <Directory Id="ApplicationProgramsFolder" Name="Inventory Control" />
      </Directory>
      <Directory Id="DesktopFolder" Name="Desktop" />
        </Directory>
    </Fragment>

  <Fragment>
    <DirectoryRef Id="ApplicationProgramsFolder">
      <Component Id="ApplicationShortcut" Guid="9bd13330-6540-406f-a3a8-d7f7c69ae7f9">
        <Shortcut Id="ApplicationStartMenuShortcut" Name="Inventory Control" Description="Inventory Control" Target="[INSTALLFOLDER]Inventory Control.exe" WorkingDirectory="INSTALLFOLDER" />
        <RemoveFolder Id="RemoveApplicationProgramsFolder" Directory="ApplicationProgramsFolder" On="uninstall" />
        <RegistryValue Root="HKCU" Key="Software\Inventory Control" Name="installed" Type="integer" Value="1" KeyPath="yes" />
      </Component>
    </DirectoryRef>
    <DirectoryRef Id="DesktopFolder">
      <Component Id="ApplicationShortcutDesktop" Guid="cde1e030-eb64-49a5-b7b8-400b379c2d1a">
        <Shortcut Id="ApplicationDesktopShortcut" Name="Inventory Control" Description="Inventory Control" Target="[INSTALLFOLDER]Inventory Control.exe" WorkingDirectory="INSTALLFOLDER" />
        <RemoveFolder Id="RemoveDesktopFolder" Directory="DesktopFolder" On="uninstall" />
        <RegistryValue Root="HKCU" Key="Software\Inventory Control" Name="installed" Type="integer" Value="1" KeyPath="yes" />
      </Component>
    </DirectoryRef>
  </Fragment>

    <Fragment>
        <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
            <!-- TODO: Remove the comments around this Component element and the ComponentRef below in order to add resources to this installer. -->
            <!-- <Component Id="ProductComponent"> -->
                <!-- TODO: Insert files, registry keys, and other resources here. -->
            <!-- </Component> -->
            <Component Id="Inventory_Control.exe" Guid="0a7e7061-201b-4d49-adeb-4449e9c4da3e">
              <File Id="Inventory_Control.exe" Name="Inventory Control.exe" Source="$(var.Inventory Control_TargetDir)Inventory Control.exe" />
            </Component>
            <Component Id="Inventory_Control.exe.config" Guid="28323615-8159-4116-b1ac-e29a70bf2593">
              <File Id="Inventory_Control.exe.config" Name="Inventory Control.exe.config" Source="$(var.Inventory Control_TargetDir)Inventory Control.exe.config" />
            </Component>
            <Component Id="System.Windows.Controls.Input.Toolkit.dll" Guid="7d678201-767a-416b-b645-b2cb7d514893">
              <File Id="System.Windows.Controls.Input.Toolkit.dll" Name="System.Windows.Controls.Input.Toolkit.dll" Source="$(var.Inventory Control_TargetDir)System.Windows.Controls.Input.Toolkit.dll" />
            </Component>
            <Component Id="System.Data.SQLite.dll" Guid="178a5aef-c027-4215-81ae-f148ab6cd472">
              <File Id="System.Data.SQLite.dll" Name="System.Data.SQLite.dll" Source="$(var.Inventory Control_TargetDir)System.Data.SQLite.dll" />
            </Component>
            <Component Id="Zen.Barcode.Core.dll" Guid="20e34fc3-0066-4ffd-b401-518bc1177098">
              <File Id="Zen.Barcode.Core.dll" Name="Zen.Barcode.Core.dll" Source="$(var.Inventory Control_TargetDir)Zen.Barcode.Core.dll" />
            </Component>
            <Component Id="WPFToolkit.dll" Guid="8d974e65-defb-4675-b9e0-ff617e5ab1da">
              <File Id="WPFToolkit.dll" Name="WPFToolkit.dll" Source="$(var.Inventory Control_TargetDir)WPFToolkit.dll" />
            </Component>
        </ComponentGroup>
    </Fragment>

  <Fragment>
    <ComponentGroup Id="Database_files" Directory="Database">
      <Component Id="Database_inventory_control.db" Guid="0104b919-0aa9-4dc5-9492-14c474d97cf1">
        <File Id="Database_inventory_control.db" Name="inventory_control.db" Source="$(var.Inventory Control_TargetDir)Database\inventory_control.db" />
      </Component>
    </ComponentGroup>
  </Fragment>
</Wix>

1 Ответ

0 голосов
/ 14 сентября 2018

SQLite.Interop.dll : файл SQLite.Interop.dll должен быть установлен вместе с остальными файлами времени выполнения для правильной работы SQLite.

Существует два варианта файла: x86 и x64.Вероятно, рекомендуется установить оба файла в соответствующие папки:

Иерархия папок вашей установки - макет:

  • YourBinary.exe
  • x86\SQLite.Interop.dll
  • x64\SQLite.Interop.dll
  • System.Data.SQLite.dll
  • Etc...

Расположение БД для чтения-записи : И тогда ваша база данных должна храниться в доступном для записи пути (или вам нужно сделать путь доступным для записи для обычных пользователей, используя настраиваемые разрешения ACL - что никогда не было бы хорошей идеей).

Исключения : Очевидно, try - catch подключение к вашей базе данных, обновление и код доступа для обнаружения подобных проблем.


  1. путаница в папке : есть ли файл базы данных внутри папки базы данных?Похоже, файл inventory_control.db установлен в основную папку приложения, а не в эту подпапку База данных ?

    • Может быть, этот файлбыл сгенерирован application.exe в неправильной папке?
    • Или, может быть, вы дублировали файл в главной папке для тестирования?
  2. Жестко закодированные грехи Dev-Box? : Что говорится в Inventory Control.exe.config?

    • Есть ли там соответствующие настройкичто может переопределить значения вашего кода?
    • Может ли быть там жестко запрограммированный грех dev-box?
  3. Path Builder: Я предполагаю, что у вас есть "сообщения в ящике" пути от приложения во время запуска, чтобы убедиться, что они правильные?Мне нравится копировать путь и сделать Start => Run и вставить путь, чтобы увидеть, что он открывается.Нажмите CTRL + C, когда появится окно сообщения.Вставьте в Блокнот.Извлеките путь и попробуйте его в Start => Run.

    • string path = currentPath.Substring(0, currentPath.Length - 21);.Не очень сложно жестко кодировать количество символов в имени файла, чтобы получить путь к родительскому каталогу?
    • Не могли бы вы улучшить его, используя Path.GetDirectoryName(currentPath)?
    • Или, может быть, даже: string dir = currentPath.Substring(0,currentPath.LastIndexOf('\\'));
  4. Присоединить отладчик и двоичные файлы отладки? : Может быть, вы могли бы установить двоичные файлы отладки и подключить их для отладки, как описаноздесь: wix c # приложение не запускается после установки .Просто чтобы получить настоящий пошаговый сеанс отладки.

  5. Пробелы : Эта строка подключения к базе данных.Нужны ли кавычки вокруг его пути?Как в "дорожке с пробелами"?У вас может не быть пробелов в путях для вашего проекта Visual Studio, но при установке в них есть пробелы.


Эта конструкция в вашем источнике выглядит странно, почемуэто необходимо?

1128 <?define Inventory Control_TargetDir=$(var.Inventory Control.TargetDir)?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...