Dynamic code execution on WinRT in Windows 8 (either C++ or .NET/C#)?

后端 未结 9 1459
谎友^
谎友^ 2021-01-02 04:12

Does WinRT under windows 8 metro allow you to dynamically load and execute code? For example, is it possible to download a dll into memory or to isolated storage and run cod

9条回答
  •  别那么骄傲
    2021-01-02 04:48

    Example of dynamic assembly loading from AppX package directory (from MSDN Forums):

    private async Task> GetAssemblyListAsync()
    {
        var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
    
        List assemblies = new List();
        foreach (StorageFile file in await folder.GetFilesAsync())
        {
            if (file.FileType == ".dll" || file.FileType == ".exe")
            {
                var name = file.Name.Substring(0, file.Name.Length - file.FileType.Length);
                Assembly assembly = Assembly.Load(new AssemblyName() { Name = name });
                assemblies.Add(assembly);
            }
        }
    
        return assemblies;
    }
    

    The assemblies must be added to the application package. You can't download them from external source.

    However, this approach does not work in .NET Native, because everything is merged into a single DLL. You should save a list of assembly names somewhere (in a simple file inside Assets) and call Assembly.Load for each item.

    Example of dynamic assembly listing in debug mode and predefined array of assembly names in release mode (.NET Native tool chain).

    #if DEBUG
    using Windows.Storage;
    #endif
    
        // ...
    
        IEnumerable assemblyNames;
    
    #if DEBUG
        assemblyNames = Windows.ApplicationModel.Package.Current.InstalledLocation.GetFilesAsync().AsTask().Result
            .Where(file => file.FileType == ".dll" && file.Name.Contains("Business"))
            .Select(file => file.Name.Substring(0, file.Name.Length - file.FileType.Length));
    #else
        assemblyNames = new[] { "California.Business", "Colorado.Business" };
    #endif
    
        foreach (var name in assemblyNames)
        {
            var assembly = Assembly.Load(new AssemblyName() { Name = name });
    
            // Load required types.
            // ...
    
        }
    

提交回复
热议问题