c# - Exe 文件不是从具有数据库连接的 Windows 服务运行?

标签 c# windows winforms entity-framework-4 windows-services

我已经创建了一个 Windows 应用程序。当我手动执行我的可执行文件时它工作正常,但是当我使用 Windows 服务运行我的 exe 时它显示提供失败错误。我正在使用 Entity Framework 。 Entity Framework 有什么问题吗?

这是我的代码:

   private void Threadfun()
    {
        try
        {               
            System.Diagnostics.Process.Start(@"D:\V-Tec\bin\Debug\VibrantIndexerForm.exe");
            if (System.IO.File.Exists(@"D:\VibrantIndexerSetup\MarcExport1.txt"))
            {
            }
            else
            {
                System.IO.File.Create(@"D:\VibrantIndexerSetup\MarcExport1.txt").Dispose();
            }

            System.IO.File.WriteAllText(@"D:\VibrantIndexerSetup\MarcExport1.txt", System.DateTime.Now.ToString());
            System.Threading.Thread.Sleep(100);
        }
        catch (Exception ex)
        {
        }     
    } 

 private void time_Elapsed(object sender, ElapsedEventArgs e)
    {

        m_thread = new System.Threading.Thread(new System.Threading.ThreadStart(Threadfun));
        if (m_thread.IsAlive)
        {
        }
        else
        {
            m_thread.Start();
        }
    }

    protected override void OnStart(string[] args)
    {
        if (time.Enabled == false)
        {    
            time.Elapsed += new ElapsedEventHandler(time_Elapsed);
            time.Interval = 2000;
            time.Enabled = true;
        }
    }

    protected override void OnStop()
    {
        time.Enabled = false;  
    }

我检查了我的网络服务并将异常消息打印到我的记事本中,发现了这个错误:

The underlying provider failed on Open.

但我只在作为 Windows 服务运行时遇到此错误。如果我手动运行我的 exe,它工作正常。是否需要在Windows服务中添加引用?

最佳答案

我还通过 Windows 服务启动我的应用程序。看看我的代码能不能帮到你

 public class WindowsApi
{

    [DllImport("Wtsapi32.dll", EntryPoint = "WTSQueryUserToken", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool WTSQueryUserToken(uint SessionId, ref IntPtr phToken);

    [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUserW", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool CreateProcessAsUser([InAttribute()]IntPtr hToken, InAttribute(), MarshalAs(UnmanagedType.LPWStr)]string lpApplicationName, [InAttribute(), MarshalAs(UnmanagedType.LPWStr)] string lpCommandLine, [InAttribute()] IntPtr pProcessAttributes, [InAttribute()] IntPtr lpThreadAttributes, MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, uint dwCreationFlags, [InAttribute()] IntPtr lpEnvironment, [InAttribute(), MarshalAsAttribute(UnmanagedType.LPWStr)] string pCurrentDirectory, ref STARTUPINFOW lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation);

    [StructLayout(LayoutKind.Sequential)]
    public struct SECURITY_ATTRIBUTES
    {
        public uint nLength;
        public IntPtr lpSecurityDescriptor;
        [MarshalAs(UnmanagedType.Bool)]
        public bool bInheritHandle;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct STARTUPINFOW
    {
        public uint cb;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string lpReserved;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string lpDesktop;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string lpTitle;
        public uint dwX;
        public uint dwY;
        public uint dwXSize;
        public uint dwYSize;
        public uint dwXCountChars;
        public uint dwYCountChars;
        public uint dwFillAttribute;
        public uint dwFlags;
        public ushort wShowWindow;
        public ushort cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public uint dwProcessId;
        public uint dwThreadId;
    }

} 

将下面的代码放在你的方法中

try
     {
         IntPtr UserTokenHandle = IntPtr.Zero;
         WindowsApi.WTSQueryUserToken(WindowsApi.WTSGetActiveConsoleSessionId(), ref UserTokenHandle);
         WindowsApi.PROCESS_INFORMATION ProcInfo = new WindowsApi.PROCESS_INFORMATION();
         WindowsApi.STARTUPINFOW StartInfo = new WindowsApi.STARTUPINFOW();
         StartInfo.cb = Convert.ToUInt32(System.Runtime.InteropServices.Marshal.SizeOf(StartInfo));
         string arguments = " nonGUI";
         WindowsApi.CreateProcessAsUser(UserTokenHandle, pathToExe + "\\YourAppName.exe", arguments, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref StartInfo, ref ProcInfo);

     catch (Exception ex)
     {
         //Catch excpetion
     } 

这将在当前用户帐户中创建一个进程。此代码已启动并运行文件。

希望对你有帮助!!干杯!

关于c# - Exe 文件不是从具有数据库连接的 Windows 服务运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13678306/

相关文章:

c# - Directory.Exists 保留目录句柄几秒钟

windows - 使用 PC 接收 LG Simplink 信号

windows - 如何使用批处理文件清除 json 中的字段?

.net - .NET消息框中的自定义按钮标题?

.net - 取消按钮需要第二次按下

c# - 在 .NET 的 Win Form 中嵌入不同的应用程序

c# - POCO 对象中的非空约束

c# - Unity - "SetDestination"只能在已放置在 NavMesh 上的事件代理上调用。 UnityEngine.NavMeshAgent :SetDestination(Vector3)

c# - WPF和MVVM Light-通过Messenger关闭带有按钮的子窗口

linux - 在 Windows 和 Linux 中远程重启同一网络上另一台计算机的命令?