【问题标题】:How can i generate a file automatically when another file changes?当另一个文件更改时,如何自动生成一个文件?
【发布时间】:2013-02-21 06:26:55
【问题描述】:

我的 asp.net mvc 项目中有一个 xml 文件 (resource.xml) 和一个 T4 文件 (resource.tt)将该文件转换为 .js 文件 (resource.js) 中的 json

问题是我想在 resource.xml 文件更改或保存时自动运行 t4 文件。

我知道在asp.net中有一个.resx文件,当它发生变化时,一个自定义工具会自动生成一个文件,

我想要这样的东西

更新: 在我的项目中,我在 /Resources/Resource.fr.xml 中有一个 xml 文件和一个 t4 文件,它读取 xml 文件并在 /Resources/Resource.fr.js 文件。 我希望 t4 文件在 xml 文件保存或更改时生成 .js 文件。

【问题讨论】:

标签: c# asp.net visual-studio t4 resx


【解决方案1】:

我刚刚在thread回答了这类问题

看看这个:https://github.com/thomaslevesque/AutoRunCustomTool 或 https://visualstudiogallery.msdn.microsoft.com/ecb123bf-44bb-4ae3-91ee-a08fc1b9770e 从自述文件:
安装扩展后,您应该会在每个项目项的属性上看到一个新的运行自定义工具。只需编辑此属性即可添加目标文件的名称。而已!
“目标”文件是您的 .tt 文件

【讨论】:

    【解决方案2】:

    看看 FileSystemWatcher 类。它监视文件甚至文件夹的更改。

    看这个例子:

    使用系统; 使用 System.IO; 使用 System.Security.Permissions;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Run(@"C:\Users\Hanlet\Desktop\Watcher\ConsoleApplication1\bin\Debug");  
            }
            [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
            public static void Run(string path)
            {
    
                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path =path;
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                watcher.Filter = "*.xml";
    
                watcher.Changed += new FileSystemEventHandler(OnChanged);
                watcher.Created += new FileSystemEventHandler(OnChanged);
                watcher.Deleted += new FileSystemEventHandler(OnChanged);
    
                watcher.EnableRaisingEvents = true;
    
                Console.WriteLine("Press \'q\' to quit the sample.");
                while (Console.Read() != 'q') ;
            }
    
            private static void OnChanged(object source, FileSystemEventArgs e)
            {
                if(e.FullPath.IndexOf("resource.xml") > - 1)
                    Console.WriteLine("The file was: " + e.ChangeType);
            }
        }
    }
    

    每当 resource.xml 文件发生某种变化(创建、删除或更新)时,它都会监控并捕获。祝你好运!

    【讨论】:

    • 你能告诉我更多细节吗?如何在 Visual Studio 项目中实现它并查看我的文件?
    • 谢谢,请告诉我在 Visual Studio 构建/保存文件时如何运行这些代码?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 2013-04-28
    • 2021-03-26
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    相关资源
    最近更新 更多