Beispiel #1
0
        /// <summary>释放文件夹</summary>
        /// <param name="asm"></param>
        /// <param name="prefix"></param>
        /// <param name="dest"></param>
        /// <param name="overWrite"></param>
        /// <param name="filenameResolver"></param>
        public static void ReleaseFolder(this Assembly asm, String prefix, String dest, Boolean overWrite = false, Func <String, String> filenameResolver = null)
        {
            if (asm == null)
            {
                asm = Assembly.GetCallingAssembly();
            }

            // 找到符合条件的资源
            var names = asm.GetManifestResourceNames();

            if (names == null || names.Length < 1)
            {
                return;
            }
            IEnumerable <String> ns = null;

            if (prefix.IsNullOrWhiteSpace())
            {
                ns = names.AsEnumerable();
            }
            else
            {
                ns = names.Where(e => e.StartsWithIgnoreCase(prefix));
            }

            if (String.IsNullOrEmpty(dest))
            {
                dest = ".".GetFullPath();
            }
            dest = dest.GetFullPath();

            // 开始处理
            foreach (var item in ns)
            {
                var stream = asm.GetManifestResourceStream(item);

                // 计算filename
                String filename = null;
                // 去掉前缀
                if (filenameResolver != null)
                {
                    filename = filenameResolver(item);
                }

                if (String.IsNullOrEmpty(filename))
                {
                    filename = item;
                    if (!String.IsNullOrEmpty(prefix))
                    {
                        filename = filename.Substring(prefix.Length);
                    }
                    if (filename[0] == '.')
                    {
                        filename = filename.Substring(1);
                    }

                    var ext = Path.GetExtension(item);
                    filename = filename.Substring(0, filename.Length - ext.Length);
                    filename = filename.Replace(".", @"\") + ext;
                    filename = Path.Combine(dest, filename);
                }

                if (File.Exists(filename) && !overWrite)
                {
                    return;
                }

                //var path = Path.GetDirectoryName(filename);
                //if (!path.IsNullOrWhiteSpace() && !Directory.Exists(path)) Directory.CreateDirectory(path);
                filename.EnsureDirectory(true);
                try
                {
                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }

                    using var fs = File.Create(filename);
                    IOHelper.CopyTo(stream, fs);
                }
                catch { }
                finally { stream.Dispose(); }
            }
        }