关闭

CSC动态编译,监测文件夹下改变(Windows服务形式),自动编译生成dll供web项目使用

标签: CSCwindows
146人阅读 评论(0) 收藏 举报
分类:

1 监测文件夹 下面所有改变

using System;
using System.IO;
using System.Security.Permissions;
using System.Threading;

namespace 自定义
{
public class FileWatcher
{

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public static void IsChanged()
    {

        FileSystemWatcher watcher = new FileSystemWatcher(@"C:\Users\Lucifer\Desktop\BizView\BizView.Model");
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite| NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);
        watcher.EnableRaisingEvents = true;
    }
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        Thread.Sleep(20000);
        Compiler.BeginCompiler();
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        Thread.Sleep(20000);
        Compiler.BeginCompiler();
    }
}

}

2 调用.net Framework 编译器CSC,CSC基本思想应该就是安德森.海尔斯伯格的,他一开始就是开发编译器的 代码如下
using System;
using System.Reflection;
using System.Globalization;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace 自定义
{
public class Compiler
{

    #region
    /// <summary>
    /// 动态生成dll
    /// </summary>
    #endregion
    public static void BeginCompiler()
    {

        string sss = @"/t:library /r:System.dll;System.Threading.Tasks.dll;System.Linq.dll;System.ComponentModel.dll;System.ComponentModel.DataAnnotations.dll;   /out:C:\Users\**自定义路径**\自定义生成文件名(包含文件类型) C:\Users\要编译的文件夹路径\*.cs";//编译目录下所有.cs文件
        //默认.net framework 4.0 csc路径
        string FileName = "C:/Windows/Microsoft.NET/Framework64/v4.0.30319/csc.exe";
        Process process = new Process();
        process.StartInfo.FileName = FileName;
        process.StartInfo.Arguments = sss;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.ErrorDialog = false;
        process.StartInfo.CreateNoWindow = false;
        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
        process.Start();
    }


}

}
3 文件监测作为Windows服务
Onstart()方法加入这句代码
FileWatcher.IsChanged();
服务已启动:
服务已启动:
改变目标文件夹下文件
改变目标文件夹下文件
生成Dll
这里写图片描述

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:707次
    • 积分:47
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章存档