从服务器启动应用程序会在应用程序生存期内创建打开文件

时间:2019-06-06 12:33:14

标签: c# .net file server

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

有没有一种方法可以在我的程序运行时关闭此打开的文件,使它不会出现在计算机管理中?

我的代码如下。我很乐意提出改善程序的建议,但实际上我只是在寻找一种解决方案,以阻止所有这些打开文件的出现。

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
}
}

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

我唯一能看到保持打开状态的区域是当我拉 Embedded Resource tegroup.ico时,我一直在查看是否在打开它时错过了某些东西,但是我无法读完后,可以看到关闭 ManifestResourceStream 的方法。

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

以下示例

Open File after app launch

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

1 个答案:

答案 0 :(得分:0)

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

c / c ++允许指定“ SWAPFILE”标志,该标志告诉Windows将整个内容放入页面文件中,但我不知道您将如何使用c#进行此操作,甚至不知道这样做阻止窗口始终保持打开状态(我对此表示怀疑)。

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

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

祝你好运。