/// <summary> /// Archives the exception report. /// The name of the PDF file is modified to make it easier to identify. /// </summary> /// <param name="pdfFile">The PDF file.</param> /// <param name="archiveDirectory">The archive directory.</param> public static void ArchiveException(FileInfo pdfFile, string archiveDirectory) { // Create a new subdirectory in the archive directory // This is based on the date of the report being archived DirectoryInfo di = new DirectoryInfo(archiveDirectory); string archiveFileName = pdfFile.Name; string newSubFolder = ParseFolderName(archiveFileName); try { di.CreateSubdirectory(newSubFolder); } catch (Exception ex) { // The folder already exists so don't create it } // Create destination path // Insert _EXCEPT into file name // This will make it easier to identify as an exception in the archive folder string destFileName = archiveFileName.Insert(archiveFileName.IndexOf("."), "_EXCEPT"); string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + destFileName; // Move the file to the archive directory try { pdfFile.MoveTo(destFullPath); } catch (Exception ex) { } }
protected void btnupload_Click(object sender, EventArgs e) { string aud; aud = "Audio"; string tempFolderAbsolutePath; tempFolderAbsolutePath = Server.MapPath("ShareData//"); string subFolderRelativePath = @"Audio";//@"SubTemp1"; DirectoryInfo tempFolder = new DirectoryInfo(tempFolderAbsolutePath); DirectoryInfo subFolder = tempFolder.CreateSubdirectory(subFolderRelativePath); string tempFileName = String.Concat(Guid.NewGuid().ToString(), @".MP3"); string str = Path.GetExtension(FileUpload1.PostedFile.FileName); if ((str == ".mp3") || (str == ".wav") || (str == ".wma") || (str == ".aiff") || (str == ".au")) { FileUpload1.SaveAs(subFolder.FullName + "\\" + FileUpload1.FileName); SqlConnection con = new SqlConnection(); SqlCommand cmd = new SqlCommand(); con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\CloudTest\\Irain-M\\Irain-M\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True"; con.Open(); cmd.Connection = con; cmd.CommandText = "insert into sharedetails(filename,username,date,category) values ('" + FileUpload1.FileName + "','" + Label1.Text + "','" + DateTime.Now + "','" + aud + "')"; cmd.ExecuteNonQuery(); con.Close(); ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Audio uploaded successfully!'); window.location.href = 'share.aspx';", true); } else { ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('This file format is not supported in this section!'); window.location.href = 'share.aspx';", true); } }
public static bool CopyDirectoryTree(this DirectoryInfo source, DirectoryInfo dest) { bool wasModified = false; if (!Directory.Exists(dest.FullName)) Directory.CreateDirectory(dest.FullName); foreach (FileInfo file in source.EnumerateFiles()) { var fileDest = Path.Combine(dest.ToString(), file.Name); if (!File.Exists(fileDest)) { file.CopyTo(fileDest); wasModified = true; } } foreach (DirectoryInfo subDirectory in source.GetDirectories()) { var dirDest = Path.Combine(dest.ToString(), subDirectory.Name); DirectoryInfo newDirectory = dest.CreateSubdirectory(subDirectory.Name); if (CopyDirectoryTree(subDirectory, newDirectory)) wasModified = true; } return wasModified; }
/// <summary> /// Deep copy directory /// </summary> /// <param name="source"></param> /// <param name="target"></param> public static void DeepCopy(DirectoryInfo source, DirectoryInfo target) { try { // Recursively call the DeepCopy Method for each Directory foreach (DirectoryInfo dir in source.GetDirectories()) { DirectoryInfo subDir = target.CreateSubdirectory(dir.Name); // --- IMPROVED SECTION --- // Set the security settings for the new directory same as the source dir subDir.SetAccessControl(new DirectorySecurity(dir.FullName, AccessControlSections.All)); DeepCopy(dir, target.CreateSubdirectory(dir.Name)); } // Go ahead and copy each file in "source" to the "target" directory foreach (FileInfo file in source.GetFiles()) { file.CopyTo(Path.Combine(target.FullName, file.Name), true); // allow overwrite } } catch (Exception) { throw; } }
static void Main(string[] args) { var directory = new DirectoryInfo(args[0]); var slides=directory.CreateSubdirectory("LaTeXCompiledSlides"); slides.Delete(true); slides.Create(); var latexDirectory = directory.CreateSubdirectory("LaTeX"); var files = latexDirectory.GetFiles("L*.tex"); var galleries = new List<GalleryInfo>(); var processor = new LatexProcessor(); foreach (var file in files) { var doc = processor.Parse(file); var docs = doc.Sections.Select(z => new LatexDocument { Preamble = doc.Preamble, Sections = new List<LatexSection> { z } }).ToList(); int number = 0; foreach (var e in docs) { var pdf = processor.Compile(e, latexDirectory); var targetDirectory = slides.CreateSubdirectory(file.Name + "." + number); processor.ConvertToPng(pdf, targetDirectory); galleries.Add(new GalleryInfo { Name = e.LastSection.Name, Directory=targetDirectory }); number++; } } var matcher = Matchers.ByName<VideoItem, GalleryInfo>(galleries, z => z.Name, (a, b) => a.Directory.FullName == b.Directory.FullName); var model = EditorModelIO.ReadGlobalData(directory); var root = ItemTreeBuilder.Build<FolderItem, LectureItem, VideoItem>(model); matcher.Push(root); DataBinding<VideoItem>.SaveLayer<GalleryInfo>(root, directory); }
private void CreateNewPackage(string name, string version) { var runtimeForPacking = TestUtils.GetClrRuntimeComponents().FirstOrDefault(); if (runtimeForPacking == null) { throw new InvalidOperationException("Can't find a CLR runtime to pack test packages."); } var runtimeHomePath = base.GetRuntimeHomeDir((string)runtimeForPacking[0], (string)runtimeForPacking[1], (string)runtimeForPacking[2]); using (var tempdir = new DisposableDir()) { var dir = new DirectoryInfo(tempdir); var projectDir = dir.CreateSubdirectory(name); var outputDir = dir.CreateSubdirectory("output"); var projectJson = Path.Combine(projectDir.FullName, "project.json"); File.WriteAllText(projectJson, $@"{{ ""version"": ""{version}"", ""frameworks"": {{ ""dnx451"": {{ }} }} }}"); DnuTestUtils.ExecDnu(runtimeHomePath, "restore", projectJson); DnuTestUtils.ExecDnu(runtimeHomePath, "pack", projectJson + " --out " + outputDir.FullName, environment: null, workingDir: null); var packageName = string.Format("{0}.{1}.nupkg", name, version); var packageFile = Path.Combine(outputDir.FullName, "Debug", packageName); File.Copy(packageFile, Path.Combine(PackageSource, packageName), overwrite: true); } }
static void Main(string[] args) { var srcDirectory = new DirectoryInfo(args[0]); //var dstDirectory = srcDirectory.Parent.CreateSubdirectory(srcDirectory.Name + "-converted"); var dstDirectory = new DirectoryInfo("C:\\users\\user\\AIML-output"); dstDirectory.Create(); var input = dstDirectory.CreateSubdirectory("Input"); var output = dstDirectory.CreateSubdirectory("Output"); var global = new GlobalData(); global.AfterLoad(dstDirectory); EditorModelIO.Save(global); var copying = ""; foreach (var e in srcDirectory.GetDirectories()) { var model = new EditorModel(e, srcDirectory, srcDirectory); ObsoleteModelIO.LoadAndConvert(model); var modelDst = input.CreateSubdirectory(e.Name); model.HackLocations(srcDirectory, modelDst); model.Save(); //copying += string.Format(@"copy ""{0}\{2}"" ""{1}\{2}"""+"\n", e.FullName, modelDst.FullName, "face.mp4"); //copying += string.Format(@"copy ""{0}\{2}"" ""{1}\{2}"""+"\n", e.FullName, modelDst.FullName, "desktop.avi"); var files = e.GetFiles(); copying += string.Format(@"xcopy ""{0}\AIML*.avi"" ""{1}\""" + "\n", e.FullName, output.FullName); } File.WriteAllText(dstDirectory + "\\copy.bat", copying); }
public Task Loop() { var t = new Task(async() => { var di = new System.IO.DirectoryInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); var testDir = di.CreateSubdirectory("DiffSyncTest"); if (testDir.Exists) { testDir.Delete(recursive: true); } testDir = di.CreateSubdirectory("DiffSyncTest"); GenerateItems(1000); var rng = new Random(); while (!Cancel.Token.IsCancellationRequested) { await Cycle(rng, testDir); await Task.Delay(1007); } }, Cancel.Token); t.Start(); return(t); }
// Constructor /// <summary> /// Open a profile (create if not exist) and load it. /// </summary> /// <param name="profileDirectory">The root directory of the profile</param> public CraftitudeProfile(DirectoryInfo profileDirectory) { Directory = profileDirectory; _craftitudeDirectory = Directory.CreateSubdirectory("craftitude"); _craftitudeDirectory.CreateSubdirectory("repositories"); // repository package lists _craftitudeDirectory.CreateSubdirectory("packages"); // cached package setups _bsonFile = _craftitudeDirectory.GetFile("profile.bson"); if (!_bsonFile.Exists) { ProfileInfo = new ProfileInfo(); } else { using (FileStream bsonStream = _bsonFile.Open(FileMode.OpenOrCreate)) { using (var bsonReader = new BsonReader(bsonStream)) { var jsonSerializer = new JsonSerializer(); ProfileInfo = jsonSerializer.Deserialize<ProfileInfo>(bsonReader) ?? new ProfileInfo(); } } } }
protected override void AnnotateCorpus( Corpus corpus, System.Threading.CancellationToken token) { token.ThrowIfCancellationRequested(); Guid taskId = Guid.NewGuid(); DirectoryInfo dir = new DirectoryInfo( AppDomain.CurrentDomain.BaseDirectory); dir = dir.CreateSubdirectory("Tasks"); dir = dir.CreateSubdirectory(taskId.ToString()); string dataFile = dir.FullName + "\\Corpus.crfppdata"; string outputFile = dir.FullName + "\\Output.crfppdata"; try { AnnotationProgressChangedEventArgs ePrepared = new AnnotationProgressChangedEventArgs( 1, 3, MessagePreparing); OnAnnotationProgressChanged(ePrepared); CRFPPHelper.EncodeCorpusToCRFPPData(corpus, dataFile); token.ThrowIfCancellationRequested(); AnnotationProgressChangedEventArgs eAnnotating = new AnnotationProgressChangedEventArgs( 2, 3, MessageAnnotating); OnAnnotationProgressChanged(eAnnotating); CRFPPHelper.Annotate( Model.RootPath, dataFile, outputFile, 1, 0); token.ThrowIfCancellationRequested(); AnnotationProgressChangedEventArgs eFinishing = new AnnotationProgressChangedEventArgs( 3, 3, MessageFinishing); OnAnnotationProgressChanged(eFinishing); CRFPPHelper.DecodeCorpusFromCRFPPData(corpus, outputFile); token.ThrowIfCancellationRequested(); } catch { throw; } finally { File.Delete(dataFile); File.Delete(outputFile); try { dir.Delete(); } catch { } } }
static void ModifyAppDirectory() { DirectoryInfo dir = new DirectoryInfo("."); dir.CreateSubdirectory("MyFolder"); DirectoryInfo myDataFolder = dir.CreateSubdirectory(@"MyFolder\Data"); Console.WriteLine("New folderr is {0}", myDataFolder); Console.WriteLine(); }
/// <summary> /// Create Project Folder /// <para>Programmer:Sarwan</para> /// <para>lab.uyghurdev.net</para> /// </summary> /// <param name="strRootPath"></param> public void createProjectFolder(string strRootPath) { DirectoryInfo di = new DirectoryInfo(strRootPath); if (!di.Exists) { di.Create(); } di.CreateSubdirectory( Settings.PICTURE_FOLDER);//Create Picture folder in root folder di.CreateSubdirectory( Settings.SOUND_FOLER);//Create Sound folder in root folder. }
public WurmPlayer(DirectoryInfo playerDir, string name, Platform targetPlatform) { Name = name; this.playerDir = playerDir; DumpsDir = playerDir.CreateSubdirectory("dumps"); LogsDir = playerDir.CreateSubdirectory("logs"); ScreenshotsDir = playerDir.CreateSubdirectory("screenshots"); ConfigTxt = new FileInfo(Path.Combine(playerDir.FullName, "config.txt")); File.WriteAllText(ConfigTxt.FullName, string.Empty); Logs = new WurmLogs(LogsDir, targetPlatform); }
static void ModifyAppDirectory() { DirectoryInfo dir = new DirectoryInfo(@"C:\"); // Create \MyFolder off application directory. dir.CreateSubdirectory("MyFolder"); // Create \MyFolder2\Data off application directory. DirectoryInfo myDataFolder = dir.CreateSubdirectory(@"MyFolder2\Data"); Console.WriteLine("New Folder is: {0}", myDataFolder); }
public void Export(string dir) { throw new NotImplementedException(); DirectoryInfo exportDir = new DirectoryInfo(dir); Dictionary<World, tempDictTwo> dict = new Dictionary<World, tempDictTwo>(); var maps = exportDir.CreateSubdirectory("Maps"); var graphics = exportDir.CreateSubdirectory("Graphics"); var data = exportDir.CreateSubdirectory("Data"); foreach (var world in this.WorldsList) { maps.CreateSubdirectory(world.Value.Name); graphics.CreateSubdirectory(world.Value.Name); tempDictTwo td = new tempDictTwo(); foreach (var map in world.Value.MapList) { tempStorage t = new tempStorage(); t.oldTexture = map.Value.Map.TextureName; t.oldPath = map.Value.MapFileLocation; td.dict.Add(map.Value.Map, t); var pictStrings = map.Value.Map.TextureName.Split(new char[] { '\\', '.' }); string imageExt = pictStrings.Last(); map.Value.MapFileLocation = Path.Combine (world.Value.Name, map.Value.Map.Name + ".xml"); String newTexturePath = Path.Combine (world.Value.Name, map.Value.Map.Name + "." + imageExt); File.Copy(Path.Combine (TileEngine.TextureManager.TextureRoot, map.Value.Map.TextureName), Path.Combine (graphics.FullName, newTexturePath), true); map.Value.Map.TextureName = newTexturePath; //map.Value.Map.Save(Path.Combine(maps.FullName, map.Value.MapFileLocation)); } dict.Add(world.Value, td); } Save(Path.Combine(data.FullName, this.FileName)); foreach (var world in this.WorldsList) { foreach (var map in world.Value.MapList) { map.Value.Map.TextureName = dict[world.Value].dict[map.Value.Map].oldTexture; map.Value.MapFileLocation = dict[world.Value].dict[map.Value.Map].oldPath; } } }
static void ModifyAppDirectory() { DirectoryInfo dir = new DirectoryInfo("."); // Create \MyFolder off initial directory. dir.CreateSubdirectory("MyFolder"); // Capture returned DirectoryInfo object. DirectoryInfo myDataFolder = dir.CreateSubdirectory(@"MyFolder2\Data"); // Prints path to ..\MyFolder2\Data. Console.WriteLine("New Folder is: {0}", myDataFolder); }
static void Main(string[] args) { string[] tabFichier = Directory.GetFiles(@"C:\Windows\Web\Wallpaper"); foreach (string fichier in tabFichier) Console.WriteLine(fichier); Console.ReadLine(); DirectoryInfo dir = new DirectoryInfo(@"C:\Windows\Web\Wallpaper"); FileInfo[] tableauImages = dir.GetFiles("*.jpg"); foreach (FileInfo f in tableauImages) { Console.WriteLine("***************************"); Console.WriteLine("Nom Fichier: {0}", f.Name); Console.WriteLine("Taille: {0}", f.Length); Console.WriteLine("Création: {0}", f.CreationTime); Console.WriteLine("Attributs: {0}", f.Attributes); Console.WriteLine("***************************\n"); } DirectoryInfo dir2 = new DirectoryInfo("."); // Mon Répertoire dir2.CreateSubdirectory(@"Mon Répertoire"); // Mon Répertoire2 DirectoryInfo nouveau = dir2.CreateSubdirectory (@"Mon Répertoire2\Données"); DriveInfo[] mesDisques = DriveInfo.GetDrives(); foreach (DriveInfo d in mesDisques) { Console.WriteLine("Nom: {0}", d.Name); // C ou D Console.WriteLine("Type: {0}", d.DriveType); // fixe if (d.IsReady) { Console.WriteLine("Espace libre: {0}", d.TotalFreeSpace); Console.WriteLine("Système fichier: {0}", d.DriveFormat); Console.WriteLine("Nom: {0}\n", d.VolumeLabel); } } Console.ReadLine(); }
public void EnumerateDirectories() { // Type var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_EnumerateDirectories")); Directory.CreateDirectory(root.FullName); root.CreateSubdirectory("Directory1"); root.CreateSubdirectory("Directory2"); // Exemples List<DirectoryInfo> result = root.EnumerateDirectories().ToList(); // Unit Test Assert.AreEqual(2, result.Count); }
private UploableErrorReportingEngine(string reportsFolderPath, int intervalOfDays, int maxNumberErrReport,bool addSnapshotToReport) { reportsFolder = new DirectoryInfo(Path.Combine(reportsFolderPath, "MiniReports")); PathUtils.TryCreatePath(reportsFolder.FullName); reportsToUploadFolder = reportsFolder.CreateSubdirectory("ToUpload"); uploadingReportsFolder = reportsFolder.CreateSubdirectory("Uploading"); processingFolder = reportsFolder.CreateSubdirectory("Processing"); lastSentItemsFileInfo = new FileInfo(Path.Combine(reportsFolder.FullName, LAST_SENT_ITEMS_FILE_NAME)); //try clear processing and uploading folder try { List<FileInfo> files = new List<FileInfo>(); //files.AddRange(uploadingReportsFolder.GetFiles("err*.zip")); //files.AddRange(uploadingReportsFolder.GetFiles("issue*.zip")); files.AddRange(uploadingReportsFolder.GetFiles("err*.*")); files.AddRange(uploadingReportsFolder.GetFiles("issue*.*")); foreach (FileInfo file in files) { file.MoveTo(Path.Combine(reportsToUploadFolder.FullName, file.Name)); } processingFolder.Delete(true); uploadingReportsFolder.Delete(true); processingFolder = reportsFolder.CreateSubdirectory("Processing"); uploadingReportsFolder = reportsFolder.CreateSubdirectory("Uploading"); } catch (Exception e) { ProcessException.Handle(e); Debug.WriteLine(e); } tools = new ProcessingJobsSharedTools(intervalOfDays, maxNumberErrReport, addSnapshotToReport, processingFolder, reportsToUploadFolder, uploadingReportsFolder, lastSentItemsFileInfo); PackageUploadManager.Initialize(tools); //Uploder uploader = new Uploder(PackageUploadManager.Instance); //uploader.TryDoUploads(); //return; ThreadPool.QueueUserWorkItem(delegate(object state) { Uploder uploader = new Uploder(PackageUploadManager.Instance); uploader.TryDoUploads(); }); }
private static void ModifyAppDierctory() { //DirectoryInfo dir = new DirectoryInfo(@"D:\C#"); //dir.CreateSubdirectory("MyZyd"); //dir.CreateSubdirectory(@"MyZyd/Img"); //dir.CreateSubdirectory(@"MyZju/zjgCampus"); DirectoryInfo dir = new DirectoryInfo("."); dir.CreateSubdirectory("MyFolder"); DirectoryInfo myDataFolder = dir.CreateSubdirectory(@"MyFolder2\Data"); Console.WriteLine("New Folder is: {0}", myDataFolder); Console.WriteLine("Directory name: {0}", myDataFolder.Name); Console.WriteLine("Creation: {0}", myDataFolder.CreationTime); Console.WriteLine("Attributes: {0}", myDataFolder.Attributes); }
private void init(DirectoryInfo d) { if (cimg.Checked==true && !Directory.Exists(Path.Combine(d.FullName, "Images"))) d.CreateSubdirectory("Images"); if (cvid.Checked == true && !Directory.Exists(Path.Combine(d.FullName, "Videos"))) d.CreateSubdirectory("Videos"); if (cdoc.Checked == true && !Directory.Exists(Path.Combine(d.FullName, "Documents"))) d.CreateSubdirectory("Documents"); if (capp.Checked == true && !Directory.Exists(Path.Combine(d.FullName, "Applications"))) d.CreateSubdirectory("Applications"); if (!Directory.Exists(Path.Combine(d.FullName, "Other"))) d.CreateSubdirectory("Other"); if (!Directory.Exists(Path.Combine(d.FullName, "Invalid"))) d.CreateSubdirectory("Invalid"); }
public void GetDirectoriesWhere() { // Type var root = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_DirectoryInfo_GetDirectories")); Directory.CreateDirectory(root.FullName); root.CreateSubdirectory("DirFizz123"); root.CreateSubdirectory("DirBuzz123"); root.CreateSubdirectory("DirNotFound123"); // Exemples DirectoryInfo[] result = root.GetDirectoriesWhere(x => x.Name.StartsWith("DirFizz") || x.Name.StartsWith("DirBuzz")); // Unit Test Assert.AreEqual(2, result.Length); }
public static void Create(string directoryPath, IFormatter formatter) { if (string.IsNullOrEmpty(directoryPath)) throw new ArgumentNullException(directoryPath); var directory = new DirectoryInfo(directoryPath); if (!directory.Exists) directory.Create(); directory.CreateSubdirectory(SimpleMessageQueueConstants.DataDirectoryName); directory.CreateSubdirectory(SimpleMessageQueueConstants.MetaDirectoryName); // Saveformatter }
public string CreateZipFromSettings(string json) { string result; try { System.Collections.Generic.IEnumerable <System.IO.DirectoryInfo> availableBrands = from path in ResourceManager.AvailableBrands(json) select new System.IO.DirectoryInfo(System.IO.Path.Combine(ResourceManager.Root, path)); System.IO.DirectoryInfo tempFolder = this.ClearTempFolder(); System.IO.DirectoryInfo subdirectory = tempFolder.CreateSubdirectory(System.Guid.NewGuid().ToString()); foreach (System.IO.DirectoryInfo brand in availableBrands) { SettingsZipper.DirectoryCopy(brand.FullName, System.IO.Path.Combine(subdirectory.FullName, brand.Name), true); } string archiveFileName = System.IO.Path.Combine(tempFolder.FullName, string.Format("{0}.zip", subdirectory.Name)); ZipFile.CreateFromDirectory(subdirectory.FullName, archiveFileName); result = archiveFileName; } catch (System.Exception ex) { Debug.WriteLine(ex.Message + " || " + ex.StackTrace); result = null; } return(result); }
public void SetVariable(string variableName, object value) { // the folder to hold variable info (type and value) DirectoryInfo variableFolder = new DirectoryInfo(VarDir.FullName + @"\" + SpecialSymbols.Encode(variableName)); if (!variableFolder.Exists) variableFolder.Create(); foreach (DirectoryInfo subdir in variableFolder.GetDirectories()) { subdir.Delete(); } // variable type (first subdirectory -- we will label with 1 to be sure) variableFolder.CreateSubdirectory("1 " + SpecialSymbols.Encode(value.GetType().ToString())); // if it's a string more than our max folder size, we'll break it down into sections if (value.ToString().Length > MAX_FOLDER_SIZE) { int folderNum = 2; foreach (string substring in SplitByLength(value.ToString(), MAX_FOLDER_SIZE)) { variableFolder.CreateSubdirectory(folderNum.ToString() + " " + SpecialSymbols.Encode(substring)); folderNum++; } } else { variableFolder.CreateSubdirectory("2 " + SpecialSymbols.Encode(value.ToString())); } }
/// <summary> /// Creates the directory for writing test files. We use the %TEMP% directory here. /// </summary> /// <param name="folder">The folder.</param> /// <returns></returns> public static DirectoryInfo CreateDirectory(string folder) { var path = //Environment.CurrentDirectory; Path.Combine(Path.GetTempPath(), "DatabaseSchemaReader"); var directory = new DirectoryInfo(path); if (!directory.Exists) { directory.Create(); } if (directory.GetDirectories(folder).Any()) { //if it's already there, clear it out var sub = directory.GetDirectories(folder).First(); try { sub.Delete(true); } catch (UnauthorizedAccessException) { //can't access it, carry on } } var subdirectory = directory.CreateSubdirectory(folder); //because it may not actually have been created... if (!subdirectory.Exists) subdirectory.Create(); return subdirectory; }
/// <summary> /// Writes index files into the specified directory. /// </summary> /// <param name="indexDirectory">The directory into which the index files should be written.</param> /// <param name="recordMapper">The mapper for the records.</param> /// <param param name="records">The records which should be written.</param> public void WriteDirectory(DirectoryInfo indexDirectory, IRecordMapper<string> recordMapper, IEnumerable<IReferenceRecord> records) { if (!indexDirectory.Exists) { indexDirectory.Create(); } var directoryNames = new HashSet<string>(); foreach (var directory in indexDirectory.GetDirectories()) { if (!directoryNames.Contains(directory.Name)) { directoryNames.Add(directory.Name); } } foreach (var record in records) { var directoryName = recordMapper.Map(record); if (!directoryNames.Contains(directoryName)) { indexDirectory.CreateSubdirectory(directoryName); directoryNames.Add(directoryName); } // Write index files into the index directory } }
public static void CopyAll(DirectoryInfo source, DirectoryInfo target, String RenameToken) { // Check if the target directory exists, if not, create it. if (Directory.Exists(target.FullName) == false) { Directory.CreateDirectory(target.FullName); } // Copy each file into it’s new directory. foreach (FileInfo fi in source.GetFiles()) { Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name); var returnInfo = fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true); } // Copy each subdirectory using recursion. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) { DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); CopyAll(diSourceSubDir, nextTargetSubDir, RenameToken); } }
/// <summary> /// The normal PDF archival method. /// </summary> /// <param name="pdfFile">The PDF file.</param> /// <param name="archiveDirectory">The archive directory.</param> public static void ArchiveNormal(FileInfo pdfFile, string archiveDirectory) { // Create a new subdirectory in the archive directory // This is based on the date of the report being archived DirectoryInfo di = new DirectoryInfo(archiveDirectory); string archiveFileName = pdfFile.Name; string newSubFolder = ParseFolderName(archiveFileName); try { di.CreateSubdirectory(newSubFolder); } catch (Exception ex) { // The folder already exists so don't create it } // Create destination path string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + pdfFile.Name; // Move the file to the archive directory try { pdfFile.MoveTo(destFullPath); } catch (Exception ex) { // Unable to move the PDF to the archive } }
// Taken from: http://xneuron.wordpress.com/2007/04/12/copy-directory-and-its-content-to-another-directory-in-c/ public static void CopyDirectoryAll(DirectoryInfo source, DirectoryInfo target) { // Check if the target directory exists, if not, create it. if (Directory.Exists(target.FullName) == false) { Directory.CreateDirectory(target.FullName); } // Copy each file into it’s new directory. foreach (FileInfo fi in source.GetFiles()) { Trace.WriteLine(String.Format(@"Copying {0}{1}", target.FullName, fi.Name)); fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true); } // Copy each subdirectory using recursion. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) { // Ignore .svn directories if (diSourceSubDir.Name == ".svn") continue; DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); CopyDirectoryAll(diSourceSubDir, nextTargetSubDir); } }
/// <summary> /// Downloads one or more packages. /// </summary> /// <param name="packageContainer"> /// The packageto downloaded. /// </param> /// <param name="repositoryDirectory"> /// The directory to which to download the packages. /// </param> /// <param name="overwrite"> /// If set to <see langword="true"/>, any existing directory will be deleted. /// </param> /// <returns> /// A <see cref="Task"/> that represents the asynchronous operation /// </returns> public static async Task<DirectoryInfo> DownloadAndExtract(IArchiveContainer packageContainer, DirectoryInfo repositoryDirectory, bool overwrite) { // Create the directory into which to extract string directoryName = $"{packageContainer.Name}-{packageContainer.Revision}"; // Figure out whether that directory already exists. DirectoryInfo targetDirectory; targetDirectory = repositoryDirectory.EnumerateDirectories(directoryName).SingleOrDefault(); // If it does, proceed based on the value of the overwrite flag if (targetDirectory != null) { if (overwrite) { // Delete the directory & proceed as usual. targetDirectory.Delete(true); targetDirectory = null; } else { // Nothing left to do. return targetDirectory; } } targetDirectory = repositoryDirectory.CreateSubdirectory(directoryName); foreach (var package in packageContainer.Archives) { Console.WriteLine($"Downloading package {package.Url} for {package.HostOs}"); await package.DownloadAndExtract(targetDirectory); } return targetDirectory; }
protected void btnUpload_Click(object sender, EventArgs e) { string tempFolderAbsolutePath; tempFolderAbsolutePath = Server.MapPath("NonShareData//" + Session["UserName"].ToString());// @"C:\Temp"; string subFolderRelativePath = @"Document";//@"SubTemp1"; DirectoryInfo tempFolder = new DirectoryInfo(tempFolderAbsolutePath); DirectoryInfo subFolder = tempFolder.CreateSubdirectory(subFolderRelativePath); string tempFileName = String.Concat(Guid.NewGuid().ToString(), @".DOC"); string str = Path.GetExtension(FileUpload1.PostedFile.FileName); if ((str == ".docx") || (str == ".txt") || (str == ".rar") || (str == ".doc") || (str == ".ppt") || (str == ".pptx") || (str == ".xls") || (str == ".xlsx") || (str == ".accdb") || (str == ".pdf")) { FileUpload1.SaveAs(subFolder.FullName + "\\" + FileUpload1.FileName); ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Document uploaded successfully!'); window.location.href = 'nonshare.aspx';", true); } else { ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('This file format is not supported in this section!'); window.location.href = 'nonshare.aspx';", true); } }
public string PrepareDataFiles(string _datapath, params object[] initParams) { string text = (string)initParams[0]; System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(_datapath); System.IO.DirectoryInfo directoryInfo2 = directoryInfo.CreateSubdirectory(System.IO.Path.GetFileNameWithoutExtension(text)); using (ZipFile zipFile = ZipFile.Read(System.IO.Path.Combine(directoryInfo.FullName, text))) { foreach (ZipEntry current in zipFile) { current.Extract(directoryInfo2.FullName, ExtractExistingFileAction.OverwriteSilently); } } return(directoryInfo2.FullName); }
static public int CreateSubdirectory__String(IntPtr l) { try { System.IO.DirectoryInfo self = (System.IO.DirectoryInfo)checkSelf(l); System.String a1; checkType(l, 2, out a1); var ret = self.CreateSubdirectory(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public void Print(IList <FilmBox> filmBoxList) { try { Status = PrintStatus.Pending; OnStatusUpdate("Preparing films for printing"); var printJobDir = new System.IO.DirectoryInfo(PrintJobFolder); if (!printJobDir.Exists) { printJobDir.Create(); } if (filmBoxList.Count > 0) { FilmSession filmSession = filmBoxList[0].FilmSession; DicomFile dcmFile = new DicomFile(filmSession); dcmFile.Save(string.Format(@"{0}\FilmSession.dcm", printJobDir)); } for (int i = 0; i < filmBoxList.Count; i++) { var filmBox = filmBoxList[i]; var filmBoxDir = printJobDir.CreateSubdirectory(string.Format("F{0:000000}", i + 1)); filmBox.Save(filmBoxDir.FullName); //generate jpg image var combineJpgFile = string.Format(@"{0}\View.jpg", filmBoxDir.FullName); CombineImages(filmBox, combineJpgFile); } FilmSessionLabel = filmBoxList.First().FilmSession.FilmSessionLabel; Status = PrintStatus.Done; } catch (Exception ex) { Status = PrintStatus.Failure; ErrorMessage = ex.Message; OnStatusUpdate("Print failed"); DeleteJobFolder(); } }
public static void DirectoryInfoTest() { Console.WriteLine("\n ------------ DIRECTORYINFO CLASS TEST ++++++++++++ "); var path = Directory.GetCurrentDirectory() + "\\DirInfo"; var path2 = Directory.GetCurrentDirectory() + "\\DirInfo2"; /*Creation */ DirectoryInfo di = new System.IO.DirectoryInfo(path); // via ctrol di.Create(); di.CreateSubdirectory("SubDir"); var dinfo = Directory.CreateDirectory(path + "\\newDir"); //via Directory.CreateDirectory FileAttributes fileAttributes = di.Attributes; //enum Console.WriteLine(fileAttributes.ToString()); //di.CreateObjRef todo: wtf Console.WriteLine("Created: {0}", di.CreationTime.ToShortTimeString()); //di.Delete(); //di.EnumerateDirectories(); var dirs = di.EnumerateDirectories(searchPattern: "*", searchOption: SearchOption.AllDirectories);// IEnumerable<DirInfo> Parallel.ForEach(dirs, (dir) => { Console.WriteLine(dir); }); var files = di.EnumerateFiles(searchPattern: "*.txt"); // IEnumerable<FileInfo> Parallel.ForEach(files, (file) => { Console.WriteLine(file); });; IEnumerable <FileSystemInfo> filesSystemInfo = di.EnumerateFileSystemInfos(searchPattern: "*"); Console.WriteLine("Exists: {0} ", di.Exists); Console.WriteLine("Extension: {0}", di.Extension); Console.WriteLine(di.FullName); DirectoryInfo[] dis = di.GetDirectories(); di.GetFiles(searchOption: SearchOption.AllDirectories, searchPattern: "*.txt"); // object lts = di.GetLifetimeService(); todo: wtf //di.GetObjectData() wtf //di.MoveTo() di.InitializeLifetimeService(); //todo }
public void InstallModule(string smodulename, bool bIsOPCServer) { try { // Find registry file associated System.IO.FileInfo[] regfiles = m_ConfFolder.GetFiles(smodulename + "*.REG"); foreach (System.IO.FileInfo reg in regfiles) { RegisterRegFile(reg.FullName); } } catch { Error("Catch exception: Register key for " + smodulename); } try { if (bIsOPCServer == true) { // Register OPC Server RegisterOPCHMI(smodulename); } } catch { Error("Catch exception: Register OPC Server for " + smodulename); } try { // Create Directories m_TracesDirectory.CreateSubdirectory(smodulename); m_RecorderDirectory.CreateSubdirectory(smodulename); } catch { Error("Catch exception: create directories for " + smodulename); } }
/********************************************************************************/ //***Copia todos arquivos de um diretório para outro com progress****************/ /********************************************************************************/ public void Copia_Todos_Arquivos_2(System.IO.DirectoryInfo origem, System.IO.DirectoryInfo destino, System.Windows.Forms.ProgressBar prb, System.Windows.Forms.ProgressBar prb_arquivo) { if (origem.FullName.ToLower() == destino.FullName.ToLower()) { return; } if (!System.IO.Directory.Exists(destino.FullName)) { try { System.IO.Directory.CreateDirectory(destino.FullName); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); log.Add(e.Message); } } foreach (System.IO.FileInfo fi in origem.GetFiles()) { try { CustomFileCopier copia = new CustomFileCopier(fi.FullName, Path.Combine(destino.ToString(), fi.Name)); copia.Copy(prb_arquivo); prb.PerformStep(); //Console.WriteLine(@"Copiando ... {0}\{1}", destino.FullName, fi.Name); //fi.CopyTo(System.IO.Path.Combine(destino.ToString(), fi.Name), true); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); log.Add(e.Message); } } foreach (System.IO.DirectoryInfo diSourceSubDir in origem.GetDirectories()) { System.IO.DirectoryInfo nextTargetSubDir = destino.CreateSubdirectory(diSourceSubDir.Name); Copia_Todos_Arquivos_2(diSourceSubDir, nextTargetSubDir, prb, prb_arquivo); } }
public System.IO.DirectoryInfo checkOrCreateSubdir(string parentpath, string subdirname) { string endSeparatorlessParentPath = this.removeFinalSlashes(parentpath); System.IO.DirectoryInfo fullpath = new System.IO.DirectoryInfo(endSeparatorlessParentPath + System.IO.Path.DirectorySeparatorChar + subdirname); if (fullpath.Exists) //subdir already exists, do nothing { return(fullpath); } System.IO.DirectoryInfo parentdir = fullpath.Parent; if (!parentdir.Exists) //if parent does not exist, do not attempt to create subdir at all { Console.WriteLine("Cannot locate/create directory (" + fullpath.FullName + "). Parent (" + parentdir.FullName + ") doesn't exist either."); return(null); } Console.Write("Output path \"" + fullpath.FullName + "\" does not exist. Would you like Scientrace to create it? [y/N]"); // try { ConsoleKeyInfo readk = Console.ReadKey(); Console.WriteLine(); if ((readk.KeyChar == 'y') || (readk.KeyChar == 'Y')) { System.IO.DirectoryInfo subdir = parentdir.CreateSubdirectory(subdirname); if (subdir.Exists) { Console.Write("Subdirectory \"" + subdir.FullName + "\" was succesfully created."); return(subdir); } else { Console.WriteLine("ERROR Creating directory"); return(null); } } //} catch { //throw new Exception("Cannot \"Console.ReadKey()\", perhaps Windows doesn't properly support consoles?"); //} Console.WriteLine("WARNING: " + fullpath.FullName + " was NOT created."); return(null); }
/********************************************************************************/ //***************Copia todos arquivos de um diretório para outro*****************/ /********************************************************************************/ public void Copia_Todos_Arquivos(System.IO.DirectoryInfo origem, System.IO.DirectoryInfo destino) { if (origem.FullName.ToLower() == destino.FullName.ToLower()) { return; } if (!System.IO.Directory.Exists(destino.FullName)) { try { System.IO.Directory.CreateDirectory(destino.FullName); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); log.Add(e.Message); } } foreach (System.IO.FileInfo fi in origem.GetFiles()) { try { Console.WriteLine(@"Copiando ... {0}\{1}", destino.FullName, fi.Name); fi.CopyTo(System.IO.Path.Combine(destino.ToString(), fi.Name), true); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); log.Add(e.Message); } } foreach (System.IO.DirectoryInfo diSourceSubDir in origem.GetDirectories()) { System.IO.DirectoryInfo nextTargetSubDir = destino.CreateSubdirectory(diSourceSubDir.Name); Copia_Todos_Arquivos(diSourceSubDir, nextTargetSubDir); } }
public void SaveGaleryToDevice() { if (!System.IO.File.Exists(Application.persistentDataPath + "/Yetrem/Gallery/")) { if (!System.IO.File.Exists(Application.persistentDataPath + "/Yetrem/")) { System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(Application.persistentDataPath); d.CreateSubdirectory("Yetrem"); } System.IO.DirectoryInfo t = new System.IO.DirectoryInfo(Application.persistentDataPath + "/Yetrem/"); t.CreateSubdirectory("Gallery"); } EraseAllDeviceGalleryDrawings(); string path = Application.persistentDataPath + "/Yetrem/Gallery/"; int i = 0; foreach (Sprite drawing in GalleryPictures) { System.IO.File.WriteAllBytes(path + "image" + i + ".jpg", drawing.texture.EncodeToJPG()); i++; } }
public void StartRending(System.IO.DirectoryInfo baseTempDir, List <VocalUtau.Calculators.NoteListCalculator.NotePreRender> NList, string RendToWav = "") { _IsRending = true; _ExitRending = false; if (RendingStateChange != null) { RendingStateChange(this); } string ProcessIDStr = Process.GetCurrentProcess().Id.ToString(); DirectoryInfo tempDir = baseTempDir.CreateSubdirectory("temp"); DirectoryInfo cacheDir = baseTempDir.CreateSubdirectory("cache"); string TrackFileName = tempDir.FullName + "\\Track_" + CacheSignal + ".wav"; FileStream Fs; headSize = InitFile(out Fs, TrackFileName); Semaphore semaphore = new Semaphore(1, 1, "VocalUtau.WavTool." + ProcessIDStr + ".Track_" + CacheSignal); ResamplerCacheDic.Clear(); Task t = Task.Factory.StartNew(() => { DoResampler(cacheDir, NList); }); for (int i = 0; i < NList.Count; i++) { while (!ResamplerCacheDic.ContainsKey(i)) { if (_ExitRending) { break; } System.Threading.Thread.Sleep(100); } if (_ExitRending) { break; } string MidFileName = ResamplerCacheDic[i]; string wavStr = String.Join(" ", NList[i].WavtoolArgList); double delay = 0; if (NList[i].passTime > 0) { delay = NList[i].passTime; } VocalUtau.WavTools.Model.Args.ArgsStruct parg = VocalUtau.WavTools.Model.Args.ArgsParser.parseArgs(NList[i].WavtoolArgList, false); Console.WriteLine("WaveAppending[" + i.ToString() + "/" + (NList.Count - 1).ToString() + "]:" + NList[i].Note + (NList[i].Note == "{R}"?"":" - " + NList[i].OtoAtom.PhonemeSymbol)); semaphore.WaitOne(); try { WavAppender.AppendWork(Fs, MidFileName, parg.Offset, parg.Length, parg.Ovr, parg.PV, delay); } catch {; } Fs.Flush(); semaphore.Release(); } _IsRending = false; long total = Fs.Length; byte[] head = IOHelper.GenerateHead((int)(total - headSize)); Fs.Seek(0, SeekOrigin.Begin); Fs.Write(head, 0, head.Length); Fs.Flush(); Fs.Close(); t.Wait(); _ExitRending = false; if (RendingStateChange != null) { RendingStateChange(this); } if (RendToWav != "") { File.Copy(TrackFileName, RendToWav, true); try { File.Delete(TrackFileName); } catch {; } } }
public async Task TestSingleReflectionSyncing() { var s = new Server(); var c = ExampleClass.Random(); var sumBefore = c.TotalQuantity; var countBefore = c.SubObjects.Count; var sumSubBefore = c.TotalSubQuantity; var syncer = Factory <ExampleClass> .Create(c.Guid, c, new ExampleClass() { Guid = c.Guid }); var dict = new Dictionary <Guid, Factory <ExampleClass> .Syncer>() { { c.Guid, syncer } }; var di = new System.IO.DirectoryInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); var testDir = di.CreateSubdirectory("DiffSyncTest"); if (testDir.Exists) { testDir.Delete(recursive: true); } testDir = di.CreateSubdirectory("DiffSyncTest"); var results = await Factory <ExampleClass> .SyncDictionary(dict, async (p) => s.ReceiveMessage(p), di); syncer.ServerCheckCopy = s.ExampleDB.First().Value.First().Value; results = await Factory <ExampleClass> .SyncDictionary(dict, async (p) => s.ReceiveMessage(p), di); if (c.Revision != 1 || !syncer.IsSynced) { throw new Exception("Revision / sync status is not as expected for new item"); } if (c.TotalQuantity != sumBefore || c.SubObjects.Count != countBefore || c.TotalSubQuantity != sumSubBefore) { throw new Exception("Single item totals mismatch after creation"); } s.SaveToDisk(testDir); s.ExampleSubSyncers.Clear(); s.ExampleSyncers.Clear(); s.LoadFromDisk(testDir); { var serverSyncer = s.ExampleSyncers.First().Value.First().Value; if (s.ExampleSyncers.Count != 1 || serverSyncer.LiveObject.Guid != c.Guid || serverSyncer.LiveObject.TotalQuantity != c.TotalQuantity) { throw new Exception("Restoring server's state from disk failed"); } } syncer.LiveObject.QuantityDefault += 100.0m; syncer.LiveObject.LastUpdated = DateTime.Now; results = await Factory <ExampleClass> .SyncDictionary(dict, async (p) => s.ReceiveMessage(p), di); if (c.Revision != 2 || syncer.LiveObject.TotalQuantity != (100.0m + sumBefore) || syncer.IsSynced) { throw new Exception("Modification of an existing item failed"); } var latestRev = s.ExampleDBByRevision.Keys.Max(); syncer.ServerCheckCopy = s.ExampleDBByRevision[latestRev]; results = await Factory <ExampleClass> .SyncDictionary(dict, async (p) => s.ReceiveMessage(p), di); if (c.Revision != 2 || syncer.LiveObject.TotalQuantity != (100.0m + sumBefore) || !syncer.IsSynced) { throw new Exception("Failure to sync after modification"); } }
public async Task TestBulkUpdates() { const int ITEMNO = 500; var s = new Server(); var c = ExampleClass.RandomList(ITEMNO); var sumBefore = c.Select(i => i.TotalQuantity).Sum(); var countBefore = c.Select(i => i.SubObjects.Count).Sum(); var sumSubBefore = c.Select(i => i.TotalSubQuantity).Sum(); var dict = c.ToDictionary(i => i.Guid, i => Factory <ExampleClass> .Create(i.Guid, i, new ExampleClass() { Guid = i.Guid })); var di = new System.IO.DirectoryInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); var serverDir = di.CreateSubdirectory("DiffSyncBulkTest"); if (serverDir.Exists) { serverDir.Delete(recursive: true); } serverDir = di.CreateSubdirectory("DiffSyncBulkTest"); var clientDir = di.CreateSubdirectory("DiffSyncBulkTestClient"); if (clientDir.Exists) { clientDir.Delete(recursive: true); } clientDir = di.CreateSubdirectory("DiffSyncBulkTestClient"); var results = await Factory <ExampleClass> .SyncDictionary(dict, async (p) => s.ReceiveMessage(p), clientDir); s.SaveToDisk(serverDir); s.LoadFromDisk(serverDir); var finalSum = s.ExampleSyncers.SelectMany(i => i.Value).Select(i => i.Value).Select(i => i.LiveObject.TotalQuantity).Sum(); { if (s.ExampleSyncers.Count != ITEMNO || finalSum != sumBefore) { throw new Exception("Bulk import failed; mismatch"); } } var r = new Random(); foreach (var item in dict.Values.OrderBy(i => r.Next()).Take((int)(ITEMNO / 5)).ToList()) { var delta = (decimal)((r.NextDouble() - 0.5) * 100.0); item.LiveObject.QuantityDefault += delta; item.LiveObject.LastUpdated = DateTime.Now; sumBefore += delta; } results = await Factory <ExampleClass> .SyncDictionary(dict, async (p) => s.ReceiveMessage(p), clientDir); s.SaveToDisk(serverDir); s.LoadFromDisk(serverDir); finalSum = s.ExampleSyncers.SelectMany(i => i.Value).Select(i => i.Value).Select(i => i.LiveObject.TotalQuantity).Sum(); { if (s.ExampleSyncers.Count != ITEMNO || finalSum != sumBefore) { throw new Exception("Bulk update failed; mismatch"); } } }
public IDirectoryInfo CreateSubdirectory(string path) { return(Wrap(_inner.CreateSubdirectory(path)) !); }
public async Task TestMultipleClients(double newItemChance = 0.0, double sendPacketLoss = 0.0, double receivePacketLoss = 0.0, bool checkEveryCycle = true, bool syncEveryCycle = true, bool makeRandomChanges = false, Func <int, int, bool> isNetworkDead = null) { /* * how many new items per client on start * create new items? * make random changes? * packet loss % * check every cycle? */ // Set up 5 clients with 50 items each, go through 50 cycles, with an occasional modification. By the end all clients and the server should have the same values var s = new Server(); var clients = new List <Client>(); for (int i = 0; i < 5; i++) { clients.Add(new Client(s) { MessageRecvFailRate = receivePacketLoss, MessageSendFailRate = sendPacketLoss }); } var di = new System.IO.DirectoryInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); var rng = new Random(); const int CYCLECOUNT = 50; for (int cycle = 0; cycle < CYCLECOUNT; cycle++) { var isLastCycle = (cycle == (CYCLECOUNT - 1)); for (int i = 0; i < 5; i++) { var clientCache = di.CreateSubdirectory("DiffSyncCache_" + i.ToString()); var c = clients[i]; if (cycle == 0 /*&& i == 0*/) { clients[i].GenerateItems(50); } else if (rng.NextDouble() < newItemChance && !isLastCycle) { clients[i].GenerateItems(1); } if (isLastCycle) { c.MessageRecvFailRate = 0.0; c.MessageSendFailRate = 0.0; } else if (isNetworkDead != null && isNetworkDead(i, cycle)) { c.MessageRecvFailRate = 1.0; c.MessageSendFailRate = 1.0; } else { c.MessageRecvFailRate = receivePacketLoss; c.MessageSendFailRate = sendPacketLoss; } await c.Cycle(rng, clientCache, /* i > 0 */ !isLastCycle, makeRandomChanges); // Don't make changes on the last cycle } if (syncEveryCycle || isLastCycle) { // It may happen that in the second last cycle a new item is created but the packet is dropped, so it may take two error free cycles to fix: for (int i = 0; i < 5; i++) { var clientCache = di.CreateSubdirectory("DiffSyncCache_" + i.ToString()); var c = clients[i]; await c.Cycle(rng, clientCache, false); } } { var serverLatestItems = s.ExampleDB.Values.Select(i => i.OrderByDescending(v => v.Key).First()).ToDictionary(i => i.Value.Guid, i => i.Value); var serverTotal = serverLatestItems.Select(i => i.Value.TotalQuantity).Sum(); var serverCount = s.ExampleDB.Values.Count(); var clientRunningSum = clients.Select(c => c.RunningTotalQuantity).Sum(); var clientItems = new Dictionary <int, Dictionary <Guid, (bool, ExampleClass)> >(); for (int i = 0; i < 5; i++) { var c = clients[i]; var syncerItems = c.Syncers.ToDictionary(kvp => kvp.Key, kvp => (true, kvp.Value.LiveObject)); var storeItems = c.LocalStore.ToDictionary(kvp => kvp.Key, kvp => (false, kvp.Value)); var storeOnlyGuids = storeItems.Keys.Except(syncerItems.Keys); var res = syncerItems.Union(storeItems.Where(kvp => storeOnlyGuids.Contains(kvp.Key))).ToDictionary(k => k.Key, k => k.Value); clientItems.Add(i, res); } for (int i = 0; i < 5; i++) { var res = clientItems[i]; var clientTotal = res.Values.Select(r => r.Item2.TotalQuantity).Sum(); var clientCount = res.Values.Select(r => r).Count(); var differences = (from server in serverLatestItems from client in res where server.Key == client.Key && server.Value.TotalQuantity != client.Value.Item2.TotalQuantity select(server, client)).ToList(); var clientValues = new Dictionary <Guid, Dictionary <int, (bool, ExampleClass)> >(); for (int j = 0; j < 5; j++) { foreach (var d in differences) { if (!clientValues.ContainsKey(d.client.Key)) { clientValues.Add(d.client.Key, new Dictionary <int, (bool, ExampleClass)>()); } if (clientItems[j].ContainsKey(d.client.Key)) { clientValues[d.client.Key].Add(j, clientItems[j][d.client.Key]); } } } if (serverCount != clientCount) { if (checkEveryCycle || isLastCycle) { throw new Exception("Server count and client count mismatch"); } else { Console.WriteLine("Warning: Server count and client count mismatch"); } } var diff = serverTotal - clientTotal; if (serverTotal != clientTotal) { //int a = 0; //a++; //var clientCache = di.CreateSubdirectory("DiffSyncCache_" + i.ToString()); //await clients[i].Cycle(rng, clientCache, false); if (checkEveryCycle || isLastCycle) { throw new Exception("Server total and client total mismatch"); } else { Console.WriteLine("Warning: Server total and client total mismatch"); } } else if (serverTotal != clientRunningSum) { // Errors in the client running sum but not the client total indicates that a change has been lost or two made the same change at the same time, but that everything synced up right. /* * if (checkEveryCycle || isLastCycle) * throw new Exception("Server total and client total mismatch"); * else * Console.WriteLine("Warning: Server total and client total mismatch"); */ } } } } }
private void DoPrint(object arg) { try { Status = PrintJobStatus.Printing; OnStatusUpdate("Printing Started"); //PrintThreadParameter printThreadParametr = (PrintThreadParameter)arg; IList <FilmBox> filmBoxList = (IList <FilmBox>)arg; var printJobDir = new System.IO.DirectoryInfo(FullPrintJobFolder); if (!printJobDir.Exists) { printJobDir.Create(); } DicomFile file; List <string> autoIDList = new List <string>(); for (int i = 0; i < filmBoxList.Count; i++) { DicomUID autoID = DicomUID.Generate(); var filmBox = filmBoxList[i]; //One Film Box, One Folder //var filmBoxDir = printJobDir.CreateSubdirectory(string.Format("F{0:000000}", i + 1 )); var filmBoxDir = printJobDir.CreateSubdirectory(autoID.UID); //Film Session Relative DICOM Tag file = new DicomFile(filmBox.FilmSession); file.Save(string.Format(@"{0}\FilmSession.dcm", filmBoxDir.FullName)); FilmBoxFolderList.Add(filmBoxDir.FullName); List <string> ImageList = filmBox.SaveImage(filmBoxDir.FullName); #region PrintTask Content PrintTask printTask = new PrintTask(); printTask.FilmUID = autoID.UID; printTask.CallingIPAddress = CallingIPAddress; printTask.CallingAE = CallingAETitle; printTask.CalledAE = CalledAETitle; #region Get Film Session Level DICOM Tag, Save in PrintTag Structure printTask.NumberOfCopies = filmBox.FilmSession.NumberOfCopies; printTask.MediumType = filmBox.FilmSession.MediumType; #endregion #region Get Film Box Level DICOM Tag, Save in PrintTag Structure printTask.printUID = SOPInstanceUID.UID; printTask.BorderDensity = filmBox.BorderDensity; printTask.ImageDisplayFormat = filmBox.ImageDisplayFormat; printTask.EmptyImageDensity = filmBox.EmptyImageDensity; printTask.FilmSizeID = filmBox.FilmSizeID; printTask.FilmOrienation = filmBox.FilmOrienation; printTask.MagnificationType = filmBox.MagnificationType; printTask.MaxDensity = filmBox.MaxDensity; printTask.MinDensity = filmBox.MinDensity; printTask.SmoothingType = filmBox.SmoothingType; printTask.Trim = filmBox.Trim; printTask.PresentationLut = filmBox.PresentationLut == null ? string.Empty : filmBox.PresentationLut.ToString(); #endregion #endregion int imageCount = ImageList.Count; for (int imageIndex = 0; imageIndex < imageCount; imageIndex++) { #region PrintImage Content PrintImage printImage = new PrintImage(); printImage.FilmUID = autoID.UID; printImage.ImageBoxPosition = imageIndex; string imagePath = string.Format(@"{0}\I{1:000000}", filmBoxDir.FullName, imageIndex + 1); printImage.DicomFilePath = imagePath + ".dcm"; //Save into Table T_PrintTag if (printImage.SaveToDB() == false) { Log.Error("Print Job {0} FAIL: {1}", SOPInstanceUID.UID.Split('.').Last(), "Save PrintImage to DB Failed"); } #endregion } int index = 0; foreach (var item in filmBox.BasicImageBoxes) { if (item != null && item.ImageSequence != null && item.ImageSequence.Contains(DicomTag.PixelData)) { try { var image = new DicomImage(item.ImageSequence); image.RenderImage().AsBitmap().Save(ImageList[index]); index++; } finally { } } } //Parse DICOM File and render into Memory As image var combineJpgFile = string.Format(@"{0}\{1}" + ".jpg", FilmBoxFolderList[i], autoID.UID); int row = 0, column = 0; GetDisplayFormat(printTask.ImageDisplayFormat, ref row, ref column); CombineImages(ImageList, combineJpgFile, row, column); printTask.JpgFilmPath = combineJpgFile; //Save into Table T_PrintTag if (printTask.SaveToDB() == false) { Log.Error("Print Job {0} FAIL: {1}", SOPInstanceUID.UID.Split('.').Last(), "Save printTask to DB Failed"); } autoIDList.Add(autoID.UID); } Status = PrintJobStatus.Done; OnStatusUpdate("Printing Done"); foreach (var autoIDItem in autoIDList) { ClientStart(autoIDItem, this.CallingIPAddress, this.CallingAETitle); } } catch (Exception ex) { Status = PrintJobStatus.Failure; OnStatusUpdate("Printing failed"); Log.Error("Print Job {0} FAIL: {1}", SOPInstanceUID.UID.Split('.').Last(), ex.Message); } finally { } }
public void Init() { Processos process = new Processos(); DirectoryInfo dir = new DirectoryInfo(@"C:\\vch"); FileInfo fil = new FileInfo(@"C:\\vch\\dados.db"); int ctrlFirstExec = 0; if (dir.Exists != true) { ctrlFirstExec = 1; string user = System.Windows.Forms.SystemInformation.UserName; System.IO.DirectoryInfo folderInfo = new System.IO.DirectoryInfo("C:\\"); DirectorySecurity ds = new DirectorySecurity(); ds.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Modify, AccessControlType.Allow)); ds.SetAccessRuleProtection(false, false); folderInfo.Create(ds); folderInfo.CreateSubdirectory("vch"); OrganizaTelaEvent(1); } if (fil.Exists != true) { try { AuxiliarNhibernate.AbrirSessao(); //fil.Create(); } catch (Exception e) { //System.Windows.Forms.MessageBox.Show(e.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (process.ReadPermissionFolder() == false || process.ReadPermissionFile() == false) { OrganizaTelaEvent(1); return; } var sessao = AuxiliarNhibernate.AbrirSessao(); Thread t = new Thread(process.VerificaParaAtualizar); t.Name = "UpdaterWorker"; t.Start(); if (ctrlFirstExec == 0) { var parametroDAO = new ParametroDAO(sessao); var param = parametroDAO.BuscarPorID(1);//Armazenamento.GetParametros(); int ctrl = 0; int ctrlVazio = 0; try { StaticParametros.SetGeraLogs(param.GeraLog); if (param.CaminhoToke.Contains(".ives") && param.CaminhoToke != "" && File.Exists(param.CaminhoToke)) { StaticParametros.SetDirToke(param.CaminhoToke); txtFolderToken.Text = param.CaminhoToke; DefineToken(param.CaminhoToke); ctrl++; } if (param.CaminhoDir != "") { if (Directory.Exists(param.CaminhoDir)) { txtFolderIni.Text = param.CaminhoDir; StaticParametros.SetDirOrigem(param.CaminhoDir); ctrl++; } } } catch (Exception ex) { //OrganizaTelaEvent(1); ctrlVazio = 1; } var parametroDBDAO = new ParametroDB_DAO(sessao); var paramDB = parametroDBDAO.BuscarTodos();//parametroDBDAO.BuscarPorID(1); //var paramDB = Armazenamento.GetParametrosDB(); try { if (paramDB.Count == 1) { StaticParametersDB.SetListBanco(paramDB[0]); if (paramDB[0].Grupo == 0 || paramDB[0].Token == null || paramDB[0].Token == "") { throw new Exception(); } else { StaticParametersDB.Setcurrent(paramDB[0].Id); } } else if (paramDB.Count > 1) { foreach (var p in paramDB) { StaticParametersDB.SetListBanco(p); } foreach (var p in paramDB) { if (p.Grupo == 0 || p.Token == null || p.Token == "") { throw new Exception(); } } StaticParametersDB.Setcurrent(paramDB[0].Id); } else { throw new Exception(); } StaticParametros.SetIntegraBanco(true); TxtStatusBanco.Text = "Conectado"; ctrl++; } catch (Exception ex) { StaticParametros.SetIntegraBanco(false); TxtStatusBanco.Text = "Desconectado"; if (ctrlVazio == 0) { var paramn = new Parametro { Id = 1, CaminhoDir = StaticParametros.GetDirOrigem(), CaminhoToke = StaticParametros.GetDirToke(), IntegraBanco = StaticParametros.GetIntegraBanco(), GeraLog = StaticParametros.GetGeraLogs() }; parametroDAO.Salvar(param); //Armazenamento.UpdateParametros(new Parametro { Id = 1, CaminhoDir = param.CaminhoDir, CaminhoToke = param.CaminhoToke, IntegraBanco = false }); } } if (ctrl >= 2) { try { if (txtFolderToken.Text == "") { OrganizaTelaEvent(1); } else { OrganizaTelaEvent(2); } //Job(); if (StaticParametros.GetDirOrigem() != null && StaticParametros.GetDirOrigem() != "") { process.CriarPastas(); } } catch (Exception ex) { OrganizaTelaEvent(1); } } else { Thread Tproc = new Thread(process.LimpaLog); Tproc.Start(); OrganizaTelaEvent(1); } } sessao.Close(); if (process.WritePermissionFolder() == false || process.WritePermissionFile() == false) { OrganizaTelaEvent(1); } }
/// <summary> /// 写入当前切片级别地理坐标系切片 /// </summary> /// <param name="i"></param> /// <param name="tileFileInfo"></param> /// <param name="outPutDir"></param> public static void WriteGeoLevel(int i, TileFileInfo tileFileInfo, string outPutDir) { IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory(); IWorkspace pWs = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(tileFileInfo.filePath), 0); IFeatureClass pFeatureClass = (pWs as IFeatureWorkspace).OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(tileFileInfo.filePath)); IFeatureLayer featureLayer = new FeatureLayerClass { FeatureClass = pFeatureClass }; IDataset dataSet = (IDataset)pFeatureClass; featureLayer.Name = dataSet.Name; IMap map = new MapClass(); map.AddLayer(featureLayer); IMapControlDefault pMapControl = new MapControlClass(); pMapControl.Map = map; IActiveView pActiveView = pMapControl.ActiveView; tagRECT rect = new tagRECT(); rect.left = rect.top = 0; rect.right = 256; rect.bottom = 256; IExport pExport = null; IEnvelope pEnvelope = new EnvelopeClass(); string temp = i.ToString(); if (temp.Length < 2) { temp = "0" + temp; } System.IO.DirectoryInfo LevelDir = new System.IO.DirectoryInfo(outPutDir).CreateSubdirectory($"L{temp}"); pMapControl.MapScale = TileParam.TileParamProjCoordinateSystem.TileScales[i]; pMapControl.Refresh(); Console.WriteLine($"Level:L{temp}:分辨率{TileParam.TileParamGeoCoordinateSystem.TileResolutions[i]}"); double imageHeighy = TileParam.TileParamGeoCoordinateSystem.TileResolutions[i] * TileParam.TileParamGeoCoordinateSystem.TileSize; for (int dy = 1, iRnum = 0; TileParam.TileOriginGeo.OriginY - imageHeighy * dy > tileFileInfo.MinY - imageHeighy; dy++, iRnum++) { if (TileParam.TileOriginGeo.OriginY - imageHeighy * dy > tileFileInfo.MaxY) { continue; } string tmpy = iRnum.ToString("X"); while (tmpy.Length < 8) { tmpy = "0" + tmpy; } Console.WriteLine($"--行号:R{tmpy}"); System.IO.DirectoryInfo RowDir = LevelDir.CreateSubdirectory($"R{tmpy}"); for (int dx = 1, iCnum = 0; TileParam.TileOriginGeo.OriginX + imageHeighy * dx < tileFileInfo.MaxX + imageHeighy; dx++, iCnum++) { if (TileParam.TileOriginGeo.OriginX + imageHeighy * dx < tileFileInfo.MinX) { continue; } string tmpx = iCnum.ToString("X"); while (tmpx.Length < 8) { tmpx = "0" + tmpx; } try { pEnvelope.PutCoords(TileParam.TileOriginGeo.OriginX + imageHeighy * (dx - 1), TileParam.TileOriginGeo.OriginY - imageHeighy * dy, TileParam.TileOriginGeo.OriginX + imageHeighy * dx, TileParam.TileOriginGeo.OriginY - imageHeighy * (dy - 1)); pExport = ToExporter("PNG"); pExport.ExportFileName = RowDir.FullName + "\\C" + tmpx + ".png"; Console.WriteLine($"----列号:C{tmpx} {pExport.ExportFileName}"); pExport.Resolution = 96; IEnvelope pPixelBoundsEnv = new EnvelopeClass(); pPixelBoundsEnv.PutCoords(rect.left, rect.top, rect.right, rect.bottom); pExport.PixelBounds = pPixelBoundsEnv; //开始导出,获取DC int hDC = pExport.StartExporting(); //导出 pActiveView.Output(hDC, 96, ref rect, pEnvelope, null); //结束导出 pExport.FinishExporting(); //清理导出类 pExport.Cleanup(); RealeaseAO(pExport); RealeaseAO(pPixelBoundsEnv); } catch (Exception ex) { Helpers.ErrorHelper.PrintException(ex); } } } RealeaseAO(workspaceFactory); RealeaseAO(pWs); RealeaseAO(pFeatureClass); RealeaseAO(featureLayer); RealeaseAO(map); RealeaseAO(pMapControl); }
public void StartRending(System.IO.DirectoryInfo baseTempDir, List <VocalUtau.Calculators.BarkerCalculator.BgmPreRender> BList, string RendToWav = "") { _IsRending = true; _ExitRending = false; if (RendingStateChange != null) { RendingStateChange(this); } string ProcessIDStr = Process.GetCurrentProcess().Id.ToString(); DirectoryInfo tempDir = baseTempDir.CreateSubdirectory("temp"); DirectoryInfo cacheDir = baseTempDir.CreateSubdirectory("cache"); string TrackFileName = tempDir.FullName + "\\Bgm_" + CacheSignal + ".wav"; FileStream Fs; headSize = InitFile(out Fs, TrackFileName); Semaphore semaphore = new Semaphore(1, 1, "VocalUtau.WavTool." + ProcessIDStr + ".Bgm_" + CacheSignal); for (int i = 0; i < BList.Count; i++) { if (BList[i].DelayTime > 0) { int ByteTime = (int)(IOHelper.NormalPcmMono16_Format.AverageBytesPerSecond * BList[i].DelayTime); ByteTime -= ByteTime % 2; byte[] byteL = new byte[ByteTime]; Array.Clear(byteL, 0, ByteTime); Fs.Write(byteL, 0, ByteTime); } semaphore.WaitOne(); try { int ByteTime = (int)(IOHelper.NormalPcmMono16_Format.AverageBytesPerSecond * BList[i].PassTime); ByteTime -= ByteTime % 2; using (NAudio.Wave.AudioFileReader reader = new NAudio.Wave.AudioFileReader(BList[i].FilePath)) { int JumpLoops = ByteTime / 2; using (NAudio.Wave.Wave32To16Stream w16 = new NAudio.Wave.Wave32To16Stream(reader)) { using (NAudio.Wave.WaveStream wfmt = new NAudio.Wave.BlockAlignReductionStream(w16)) { using (NAudio.Wave.WaveStream wout = new NAudio.Wave.WaveFormatConversionStream(IOHelper.NormalPcmMono16_Format, wfmt)) { while (wout.Position < wout.Length) { if (_ExitRending) { break; } byte[] by = new byte[2]; int rd = wout.Read(by, 0, 2); if (JumpLoops > 0) { JumpLoops--; } else { Fs.Write(by, 0, 2); } /* for (int w = 1; w < w16.WaveFormat.Channels; w++) * { * int rdr = w16.Read(by, 0, 2); * }*/ } } } } } } catch {; } Fs.Flush(); semaphore.Release(); if (_ExitRending) { break; } } _IsRending = false; long total = Fs.Length; byte[] head = IOHelper.GenerateHead((int)(total - headSize)); Fs.Seek(0, SeekOrigin.Begin); Fs.Write(head, 0, head.Length); Fs.Flush(); Fs.Close(); _ExitRending = false; if (RendingStateChange != null) { RendingStateChange(this); } if (RendToWav != "") { File.Copy(TrackFileName, RendToWav, true); try { File.Delete(TrackFileName); } catch {; } } }
/// <summary> /// Creates a subdirectory or subdirectories on the specified path. The specified /// path can be relative to this instance of the System.IO.DirectoryInfo class. /// </summary> /// <param name="path"> /// The specified path. This cannot be a different disk volume or Universal Naming /// Convention (UNC) name. /// </param> /// <returns> /// The last directory specified in path. /// </returns> /// <exception cref="System.ArgumentException"> /// path does not specify a valid file path or contains invalid DirectoryInfo /// characters. /// </exception> /// <exception cref="System.ArgumentNullException"> /// path is null. /// </exception> /// <exception cref=" <exception cref="System.IO.DirectoryNotFoundException">"> /// The specified path is invalid, such as being on an unmapped drive. /// </exception> /// <exception cref="System.IO.IOException"> /// The subdirectory cannot be created.-or- A file or directory already has the /// name specified by path. /// </exception> /// <exception cref="System.IO.PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum /// length. For example, on Windows-based platforms, paths must be less than /// 248 characters, and file names must be less than 260 characters. The specified /// path, file name, or both are too long. /// </exception> /// <exception cref="System.Security.SecurityException"> /// The caller does not have code access permission to create the directory.-or-The /// caller does not have code access permission to read the directory described /// by the returned System.IO.DirectoryInfo object. This can occur when the path /// parameter describes an existing directory. /// </exception> /// <exception cref="System.NotSupportedException"> /// path contains a colon character (:) that is not part of a drive label ("C:\"). /// </exception> public System.IO.DirectoryInfo CreateSubdirectory(string path) { return(_directoryInfo.CreateSubdirectory(path)); }