繁体   English   中英

从服务器启动应用程序会为应用程序的生命周期创建Open File

[英]Launching application from server creates Open File for lifetime of application

我在我的一个文件服务器上启动了一个程序。 启动程序后,它在计算机管理中显示为打开文件

有没有办法在程序运行时关闭这个打开的文件,这样就不会出现在计算机管理中

我的代码如下。 我很乐意接受有关改进我的程序的建议,但我真的只是在寻找一种解决方案来阻止所有这些Open Files出现。

Program.cs - 启动程序,处理启动我的应用程序的逻辑

using System;
using System.Windows.Forms;
using System.Diagnostics;

namespace IT_TaskbarApp
{
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        string programName = "TEG System Helper";

        //Process[] proc = Process.GetProcessesByName(programName);

        if (Process.GetProcessesByName(programName).Length == 1)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Primary());
        }
        else
        {
            foreach (Process p in Process.GetProcessesByName(programName))
            {
                if (Process.GetCurrentProcess().Id != p.Id)
                {
                    p.CloseMainWindow();
                    p.Close();
                    p.Kill();
                    p.Dispose();
                }
            }
            Main();
        }
    }
}
}

Primary.cs - 在系统图标中创建一个图标,我可以使用该图标发送通知并轻松访问组织内的实用程序

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

namespace IT_TaskbarApp
{
public partial class Primary : Form
{
    private NotifyIcon notifyIcon;
    private ContextMenu contextMenu;
    private MenuItem[] menuItem = new MenuItem[8];
    private IContainer components;
    //private Boolean SendNotices = true;
    private DateTime startTime = DateTime.Now;
    private DateTime currentTime;
    private Icon tegroupIcon = new Icon(Assembly.GetExecutingAssembly().GetManifestResourceStream("IT_TaskbarApp.Src.tegroup.ico"));

    private string prevNotification = "";
    private bool isRunning = true;
    private BackgroundWorker bgNotify = new BackgroundWorker();

    private const string programName = "TEG System Helper";

    public Primary()
    {
        this.FormClosing += Primary_FormClosing; //remove ghost icon in taskbar

        ForeColor = Color.Blue;
        BackColor = Color.Green;


        components = new Container();
        contextMenu = new ContextMenu();

        for (int i = 0; i < menuItem.Length; i++)
        {
            menuItem[i] = new MenuItem();
            menuItem[i].Index = i;
            menuItem[i].Click += new EventHandler(LoadProcess);
        }

        menuItem[0].Text = programName;
        menuItem[1].Text = "Knowledge Base";
        menuItem[2].Text = "Policies";
        menuItem[3].Text = "Feedback";
        menuItem[4].Text = "Global Shop Search";
        menuItem[5].Text = "-";
        menuItem[6].Text = "Submit Ticket";
        menuItem[7].Text = "Send Email";

        //initialize contextMenu
        contextMenu.MenuItems.AddRange(menuItem);



        // Create the NotifyIcon.
        notifyIcon = new NotifyIcon(components)
        {
            Icon = tegroupIcon,
            BalloonTipIcon = new ToolTipIcon(),
            ContextMenu = contextMenu, //the menu when right clicked
            Text = programName,
            Visible = true,
            BalloonTipTitle = programName,

        };

        notifyIcon.DoubleClick += new EventHandler(Icon_DoubleClick);

        InitializeComponent();

        bgNotify.WorkerSupportsCancellation = true;
        bgNotify.WorkerReportsProgress = true;
        bgNotify.DoWork += NotifyUser;
        bgNotify.ProgressChanged += SendNotice;
        //bgNotify.RunWorkerCompleted += BgNotify_RunWorkerCompleted; //enable this to perform an action when the thread dies
        bgNotify.RunWorkerAsync();
        //Thread tNotify = new Thread();
    }

    #region SupportedFunctions

    private void NotifyUser(object Sender, EventArgs e)
    {
        Console.WriteLine("enter");
        while (isRunning)
        {
            currentTime = DateTime.Now;
            #region DisplayCurrentTime
            if (currentTime.Hour < 10 || currentTime.Minute < 10)
            {
                if (currentTime.Hour < 10)
                {
                    if (currentTime.Minute < 10)
                    {
                        Console.WriteLine("0{0}:0{1}", currentTime.Hour, currentTime.Minute);
                    }
                    else
                    {
                        Console.WriteLine("0{0}:{1}", currentTime.Hour, currentTime.Minute);
                    }
                }
                else
                {
                    if (currentTime.Minute < 10)
                    {
                        Console.WriteLine("{0}:0{1}", currentTime.Hour, currentTime.Minute);
                    }
                }
            }
            else
            {
                Console.WriteLine("{0}:{1}", currentTime.Hour, currentTime.Minute);
            }
            #endregion

            FileStream fs = new FileStream("\\\\te-admin\\public\\TaskbarNotices.txt", FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            string noticeText = sr.ReadToEnd();
            sr.Close();
            fs.Close();

            if (noticeText != "" && noticeText != prevNotification)
            {
                prevNotification = noticeText;
                bgNotify.ReportProgress(1);
            }
            else
            {
                bgNotify.ReportProgress(2);
            }


            Console.WriteLine("Inner Text: {0}  TOF: {1}", noticeText, noticeText != "");
            Thread.Sleep(10000);
        }
    }

    private void SendNotice(object Sender, ProgressChangedEventArgs e)
    {
        if (e.ProgressPercentage == 1)
        {
            Console.WriteLine("notification sent");
            this.notifyIcon.BalloonTipText = prevNotification;
            this.notifyIcon.ShowBalloonTip(1500);
        }
    }

    private void LoadProcess(object Sender, EventArgs e)
    {
        if (Sender is MenuItem)
        {
            MenuItem tempMenu = Sender as MenuItem;

            string ProgramTag = "http://";

            switch (tempMenu.Index)
            {
                case 0: //home page
                    ProgramTag += "teg";
                    break;
                case 1: //docviewer
                    ProgramTag += "teg/docViewer";
                    break;
                case 2: //policies
                    ProgramTag += "teg/Policies";
                    break;
                case 3: //feedback
                    ProgramTag += "teg/Feedback";
                    break;
                case 4: //inventory search
                    ProgramTag = "http://searchglobalshop/inventory/index.aspx";
                    break;
                case 6: //submit ticket
                    ProgramTag = "https://timberlandgroup.on.spiceworks.com/portal/tickets";
                    break;
                case 7: //send email
                    string sendto = "admin@tewinch.com";
                    string emailSubject = "Assistance Request";
                    string emailBody = "";
                    string mailto = string.Format("mailto:{0}?Subject={1}&Body={2}", sendto, emailSubject, emailBody);
                    ProgramTag = Uri.EscapeUriString(mailto);
                    break;
            }

            /*
             Try to launch the choice the user made with the default processing method.
             Should the default method fail we try to control how the process is run.
             We open internet explorer and then we show them what to do otherwise.
             */
            #region LaunchSelectedProcess
            try
            {
                if (ProgramTag != "" && ProgramTag != "http://")
                    Process.Start(ProgramTag);
            }
            catch (System.ComponentModel.Win32Exception)
            {
                try
                {
                    if (ProgramTag.StartsWith("http://") || ProgramTag.StartsWith("https://"))
                        Process.Start("iexplore.exe", ProgramTag);
                }
                catch (System.ComponentModel.Win32Exception)
                {
                    Process.Start("control.exe", "/name Microsoft.DefaultPrograms");

                    string message = "";
                    if (tempMenu.Index <= 6)
                    {
                        message = "You must have a default browser set\n\tClick [Set Default Program]\n";

                        if (Environment.OSVersion.ToString().Contains("NT 10.")) //windows 10
                        {
                            message += "\tUnder [Web Browser] Edge is currently set as default\n\tClick on Microsoft Edge\n\tSelect the browser you use";
                        }
                        else //windows 7 -- "NT 6.1")
                        {
                            message += "Select the browser you use\n\tClick [Set this program as default]";
                        }
                    }
                    else
                    {
                        if (Environment.OSVersion.ToString().Contains("NT 10.")) //windows 10
                        {
                            message += "Please setup a default email application";
                        }
                    }

                    message += "\n\nIf this issue persists please contact your Administrator.\nPhone: 519-537-6262\nEmail: admin@tewinch.com";
                    MessageBox.Show(message, "Application Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    //if ( == DialogResult.OK)

                }
            }
            #endregion
        }
    }

    private void Icon_DoubleClick(object Sender, EventArgs e)
    {
        Process.Start("http://teg");
    }
    #endregion


    #region BuiltFunctions
    private void Primary_FormClosing(object sender, FormClosingEventArgs e)
    {
        notifyIcon.Icon = null;
        notifyIcon.Dispose();
        isRunning = false;
        Dispose(true);
    }

    private void InitializeComponent()
    {
        this.SuspendLayout();
        // 
        // Primary
        // 
        this.Icon = tegroupIcon;
        this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
        this.CausesValidation = false;
        this.ClientSize = new System.Drawing.Size(120, 23);
        this.ControlBox = false;
        this.Enabled = false;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Name = "Primary";
        this.Opacity = 0D;
        this.ShowIcon = false;
        this.ShowInTaskbar = false;
        this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
        this.ResumeLayout(false);

    }

    protected override void Dispose(bool disposing)
    {
        // Clean up any components being used.
        if (disposing)
            if (components != null)
                components.Dispose();

        base.Dispose(disposing);
    }
    #endregion
}
}

我没有在启动时取消程序,而是杀死程序的其他正在运行的实例。 我的想法是,如果程序出现任何问题,我只需启动另一个实例并解决问题。 现在不会出现太多错误,但我们将在开发此程序以便将来完成更多任务。

我可以看到唯一可以保持文件打开的区域是当我拉出一个嵌入式资源 tegroup.ico时,我想看看我是否在打开它时错过了一些东西,但是在看完之后我看不到关闭ManifestResourceStream的方法在。

任何提示/建议都会很精彩,但我再次想知道是否有办法可以关闭这些打开的文件

以下示例

应用启动后打开文件

我可能正试图解决一些使用Application.Run()的已知结果,如果是这种情况,那么请建议我可以使用的替代方案。 我的其他想法是将程序加载到内存并在本地启动它,使用服务器上的.exe作为此方法的起点。

我相信Windows不会将整个可执行文件加载到ram中。 它不仅仅是来自PE文件资源部分的文件。 exe的部分仅在引用时加载,甚至在加载要加载的所有内容之后,Windows将保持打开的文件句柄,直到进程关闭。 试图自己关闭这个句柄是个坏主意。

c / c ++允许指定一个“SWAPFILE”标志,告诉windows将整个内容放入页面文件中,但我不知道你是怎么用c#做的,我不知道这是否会阻止windows无论如何都要保持手柄打开(我对此表示怀疑)。

如果这真的很重要,iffin'我是你的exe ...我会:

  1. 检查互斥锁是否存在正在运行的实例,如果存在则退出
  2. 检查我的运行位置。
  3. 如果从temp运行,请设置我正在运行的互斥锁并运行。
  4. 如果没有从temp运行,请将自己复制到%temp%,启动该副本,然后退出。

祝好运。

暂无
暂无

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

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