【问题标题】:Launching application from server creates Open File for lifetime of application从服务器启动应用程序为应用程序的生命周期创建打开文件
【发布时间】:2019-10-21 23:30:32
【问题描述】:

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

有什么方法可以在我的程序运行时关闭这个打开的文件,这样它就不会出现在计算机管理中?

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

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 的方法。

任何提示/建议都会很棒,但我真的只是想知道是否有办法关闭这些打开的文件

以下示例

Open File after app launch

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

【问题讨论】:

    标签: c# .net file server


    【解决方案1】:

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

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

    如果这真的很重要,如果我是你的前任……我会:

    1. 检查现有正在运行的实例的互斥锁,如果存在则退出
    2. 检查我从哪里逃跑。
    3. 如果从 temp 运行,请设置一个我正在运行的互斥体,然后运行。
    4. 如果不是从 temp 运行,请将自己复制到 %temp%,启动该副本,然后退出。

    祝你好运。

    【讨论】:

    • 谢谢。这是一个很好的回应。
    • 欢迎您@CeaganP。如果你喜欢它,我会很感激你接受这个作为你的答案。 :)
    • 我仍在寻找解决方案。我应该在接下来的几个小时内知道是否是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2013-05-21
    相关资源
    最近更新 更多