public void CopyTo_DestinationDirectoryDoesExist() { var subDirectoryPath = "sub1" + Path.DirectorySeparatorChar + "sub2"; var testFilePath = Path.Combine (subDirectoryPath, "testFile.txt"); var sourceFilePath = Path.Combine (sourceDirectoryPath, testFilePath); var destinationFilePath = Path.Combine (destinationDirectoryPath, testFilePath); var sourceDirectory = new DirectoryInfo (sourceDirectoryPath); sourceDirectory.Create (); sourceDirectory.CreateSubdirectory (subDirectoryPath); File.Create (sourceFilePath).Close (); // call copyTo a second time, wanted behavior: silently overwrite directories and files Assert.That (Directory.Exists (destinationDirectoryPath), Is.False); sourceDirectory.CopyTo (destinationDirectoryPath); var lastWriteTime1 = File.GetLastWriteTime (destinationFilePath); // last write time of the copied file is 'inherited' from source file, so we have to update it System.Threading.Thread.Sleep(10); File.Create (sourceFilePath).Close (); Assert.That (Directory.Exists (destinationDirectoryPath), Is.True); sourceDirectory.CopyTo (destinationDirectoryPath); var lastWriteTime2 = File.GetLastWriteTime (destinationFilePath); // creation time does not change, when file is overwritten -> use last write time Assert.Less (lastWriteTime1, lastWriteTime2); Directory.Delete (sourceDirectoryPath, true); Directory.Delete (destinationDirectoryPath, true); }
private void SetupContentDirectory(string contentDirectory) { contentDir = new DirectoryInfo(contentDirectory); var includeFiles = new DirectoryInfo("Includes"); includeFiles.CopyTo(contentDir); }
public void CopyTo() { // Type var @this = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DirectoryInfo_CopyTo")); var copyTo = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DirectoryInfo_CopyTo2")); Directory.CreateDirectory(@this.FullName); @this.CreateSubdirectory("FizzBuzz"); var result1 = @this.GetDirectories().Length; // Exemples @this.CopyTo(copyTo.FullName); // Unit Test var result2 = copyTo.GetDirectories().Length; Assert.AreEqual(1, result1); Assert.AreEqual(1, result2); }
private void copy(DirectoryInfo source, String destination) { source.CopyTo(@destination, true); }
public static void Main() { DirectoryInfo directory = new DirectoryInfo(".\\Source"); directory.CopyTo(".\\Target", SearchOption.TopDirectoryOnly, "*");//Extension method. Is Defined below but appears to be a member of the DirectoryInfo object, directory, defined aboves }
public void WriteCommentedFiles(string outputFolder) { var pageTemplate = GetPageTemplate(); if (pageTemplate == null) { Cli.WriteLine("~Red~Could not read code coverage page template~R~"); return; } var codePageTable = new CodePageTable(); var coverageDir = GetCodeCoveragePath(outputFolder); _table.Items.Iter(x => { Cli.WriteLine("Writing coverage comments for ~Cyan~{0}~R~", x.Plugin); var pluginDir = GetCommentedFilePath(outputFolder, x.Plugin); var relativePluginDir = pluginDir.Substring(coverageDir.Length + 1); Directory.CreateDirectory(pluginDir); var codePages = new List<CodePage>(); x.Items.Iter(y => { var commentedCode = CreateCommentedCode(y); if (commentedCode == null) { return; } var codeFilename = GetRelativeCodePath(y); var page = string.Format( pageTemplate, codeFilename, HttpUtility.HtmlEncode(x.Plugin), HttpUtility.HtmlEncode(commentedCode)); var pageFilename = Path.Combine(pluginDir, GetPageFilename(y)); File.WriteAllText(pageFilename, page); var relateivePageFilename = Path.Combine(relativePluginDir, GetPageFilename(y)); codePages.Add(new CodePage(codeFilename, relateivePageFilename)); Cli.WriteLine("[~Green~+~R~] {0}", codeFilename); }); codePageTable.Add(x.Plugin, codePages); Cli.WriteLine(); }); var index = Path.Combine(coverageDir, "index.html"); File.WriteAllText(index, codePageTable.ToHtml()); var highlighterDir = new DirectoryInfo(PathHelper.GetEntryPath("SyntaxHighlighter")); highlighterDir.CopyTo(coverageDir); }
static void Main(string[] args) { string sVal; if (args.Length == 0) { Syntax(); return; } switch (args[0]) { case "static": Console.Write("\nStatic member variables\n"); S1 x1 = new S1(); // 1st instance x1.display("x1"); // print static variable x1.increment(); x1.display("x1"); // print static variable S1 x2 = new S1(); // 2nd instance x2.display("x2"); S1 x3 = new S1(); //3rd instance x3.display("x3"); x3.increment(); x3.display("x3"); x1.increment(); x1.display("x1"); x2.increment(); x2.display("x2"); x3.increment(); x3.display("x3"); x1.increment(); x1.display("x1"); x2.display("x2"); x3.display("x3"); Console.Write("Class S1: i={0}\n", S1.i); // direct access to static member variable Console.Write("\nStatic Methods\n"); S1.increment_static(); S1.display_static("Class S1"); try{ DirectoryInfo directory = new DirectoryInfo(".\\Source"); Console.WriteLine("Moving {0} to {1}", directory.FullName, ".\\Root"); directory.MoveTo(".\\Root"); DirectoryInfoExtension.CopyTo(directory, ".\\Target", SearchOption.AllDirectories, "*"); } catch (IOException e) { Console.WriteLine("ERROR: " + e.Message); Console.WriteLine("Possibly improper setup."); Console.WriteLine("In the execution directory, ensure there is a Source directory, with subdirectories, and files in those subdirectories."); Console.WriteLine("Also, no directories named Root or Target - those will be created."); } break; case "properties": // Property exercises P1 p = new P1(); p.a = 41; p.Print("a"); //p.b = 42; - would get compiler error since b is read-only p.Print("b"); Console.Write("What is the value to be added to 999999?"); sVal = Console.ReadLine(); // convert input string to int int x = System.Convert.ToInt32(sVal); try { p.c = 999999 + x; } catch (ArgumentOutOfRangeException e) { Console.Write("ERROR: " + e.Message + "\n"); break; } p.Print("c"); break; case "recursion": Console.Write("Input number of levels of recursion: "); sVal = Console.ReadLine(); if (sVal == "infinite") { // When The maximum number of stack frames supported by Visual Studio has been exceeded (5000 stack frames) // the program is terminated, and no exception is thrown; i.e. an exception is not caught here or in the inner // exception handler in the Recursion class. try { Recursion.infiniteRecursion(); } catch (StackOverflowException e) { Console.Write("ERROR: Stack Overflow\n" + e.Message); } catch (Exception e) { Console.Write("ERROR: Generic Exception\n" + e.Message); } } else { // Note that the BCL-name for this data type is System.Int16 with range -32,768 to 32,767. short recursionLevels = 0; try { recursionLevels = System.Convert.ToInt16(sVal); } catch (Exception e) { Console.Write("ERROR: " + e.Message); break; } try { Recursion.makeRecursiveCall(recursionLevels); } catch (StackOverflowException e) { Console.Write("ERROR: Stack Overflow\n" + e.Message); } catch (Exception e) { Console.Write("ERROR: Generic Exception\n" + e.Message); } } break; case "datatypes": DataTypes.Run(); DataTypes d = new DataTypes(); d.printStrings(); d.printLiterals(); break; case "conversions": System.Console.Write("Input test 16, 32, or 64: "); string s = System.Console.ReadLine(); int testNum = System.Convert.ToInt32(s); //Conversions c = new Conversions(); --> can't declare variable of static type and can't instantiate static class //c.Test(testNum); --> static member Test can't be accessed with an instance reference Conversions.Test(testNum); // this reference to Conversions causes its static constructor to be called break; case "parameters": Console.WriteLine("Swapping 'First' and 'Second'"); string first = "First"; string second = "Second"; Methods.SwapR(ref first, ref second); Console.WriteLine("By Reference: First = {0} Second = {1}", first, second); //Methods.SwapR(first, second); // still by reference? won't compile //Console.WriteLine("By Reference: First = {0} Second = {1}", first, second); first = "First"; second = "Second"; Methods.SwapV(first, second); Console.WriteLine("By Value: First = {0} Second = {1}", first, second); //Methods.SwapV(ref first, ref second); // by ref or value? won't compile //Console.WriteLine("By Value: First = {0} Second = {1}", first, second); Console.Write("\nInput the number to be squared and square rooted: "); double y = double.Parse(Console.ReadLine()); double squareRoot; squareRoot = 99; // assign value to output parameter before call - of course the compiler allows this double squared = Methods.Squares(y, out squareRoot); Console.WriteLine("Squared: {0} Square Root: {1}", squared, squareRoot); break; case "extensionmethods": try{ DirectoryInfo directory = new DirectoryInfo(".\\Source"); directory.CopyTo(".\\Target", SearchOption.AllDirectories, "*"); } catch (IOException e) { Console.WriteLine("ERROR: " + e.Message); Console.WriteLine("Possibly improper setup."); Console.WriteLine("In the execution directory, ensure there is a Source directory, with subdirectories, and files in those subdirectories."); Console.WriteLine("Also, no directories named Root or Target - those will be created."); } break; case "delegates": int[] items = new int[100]; ComparisonHandler ch; // the delegate Random random = new Random(); ch = DelegateSample.GreaterThan; // delegate method 1 for (int k = 0; k < 2; k++) { for (int i = 0; i < items.Length; i++) { items[i] = random.Next(int.MinValue, int.MaxValue); } DelegateSample.BubbleSort(items, ch); for (int i = 0; i < items.Length; i++) { Console.WriteLine(items[i]); } Console.ForegroundColor = ConsoleColor.Cyan; ch = DelegateSample.LessThan; // delegate method 2 } Console.ForegroundColor = ConsoleColor.Green; break; default: Syntax(); break; } }
public void CopyTo_SourceDirectoryDoesNotExist() { var sourceDirectory = new DirectoryInfo ("nonExistingDirectory"); try { sourceDirectory.CopyTo ("doesNotMatter"); Assert.Fail ("expected exception was not thrown"); } catch (DirectoryNotFoundException ex) { Assert.That (ex.Message, Is.EqualTo ("source directory '" + sourceDirectory.FullName + "' not found ")); } }
public void CopyTo_DestinationDirectoryDoesNotExist() { var subDirectoryPath = "sub1" + Path.DirectorySeparatorChar + "sub2"; var testFilePath = Path.Combine (subDirectoryPath, "testFile.txt"); var sourceDirectory = new DirectoryInfo (sourceDirectoryPath); sourceDirectory.Create (); sourceDirectory.CreateSubdirectory (subDirectoryPath); File.Create (Path.Combine (sourceDirectoryPath, testFilePath)).Close (); Assert.That (Directory.Exists (destinationDirectoryPath), Is.False); sourceDirectory.CopyTo (destinationDirectoryPath); Assert.That (File.Exists (Path.Combine (destinationDirectoryPath, testFilePath)), Is.True); Directory.Delete (sourceDirectoryPath, true); Directory.Delete (destinationDirectoryPath, true); }
private static void CopySourceFolders(ArchiveTask archiveTask, DirectoryInfo sourceDirectory) { var destinationDirectory = new DirectoryInfo(archiveTask.Destination); Log.Debug("Source Folder : '{0}'", sourceDirectory.FullName); Log.Debug("Destination Folder: '{0}'", destinationDirectory.FullName); sameRoot = false; if (sourceDirectory.Root.Name == destinationDirectory.Root.Name) { sameRoot = true; } const string ioftpd = ".ioFTPD"; const string ioftpdBackup = ".backup"; string sourceFileName = Misc.PathCombine(sourceDirectory.FullName, ioftpd); if (File.Exists(sourceFileName)) { string backupSource = sourceFileName + ioftpdBackup; FileInfo.DeleteFile(backupSource); File.Move(sourceFileName, backupSource); } string destinationFolder = Misc.PathCombine(destinationDirectory.FullName, sourceDirectory.Name); sourceDirectory.CopyTo(new DirectoryInfo(destinationFolder), true); string destinationFileName = Misc.PathCombine(destinationFolder, ioftpd + ioftpdBackup); if (File.Exists(destinationFileName)) { string backupDestination = Misc.PathCombine(destinationFolder, ioftpd); FileInfo.DeleteFile(backupDestination); File.Move(destinationFileName, backupDestination); } }
private static DataTable GetData(string symbol) { DataTable tblFile = new DataTable(); try { string folderPath = ConfigurationManager.AppSettings["BCTC_FolderDownload"]; //folderPath = Server.MapPath(folderPath); DirectoryInfo folder = new DirectoryInfo(folderPath); DirectoryInfo[] subFolders = folder.GetDirectories(); DirectoryInfo[] folderShowed = new DirectoryInfo[subFolders.Length]; DirectoryInfo[] folderYear = new DirectoryInfo[subFolders.Length]; DirectoryInfo[] folderOther = new DirectoryInfo[subFolders.Length]; int i = 0, j = 0; foreach (DirectoryInfo subFolder in subFolders) { if (IsNumber(subFolder.Name)) { folderYear[i] = subFolder; i++; } else { folderOther[j] = subFolder; j++; } } Array.Sort(folderYear, 0, i, new FolderSort()); folderYear.CopyTo(folderShowed, 0); for (int a = i, b = 0; a < folderOther.Length && b < j; a++, b++) { folderShowed[a] = folderOther[b]; } tblFile.Columns.Add("FileName"); tblFile.Columns.Add("LinkFile"); tblFile.Columns.Add("Time"); tblFile.Columns.Add("LoaiBaoCao"); DataRow dr; foreach (DirectoryInfo subFolder in folderShowed) { string searchPattern = ""; searchPattern = symbol + "_"; FileInfo[] files = subFolder.GetFiles(searchPattern + "*", SearchOption.TopDirectoryOnly); Array.Sort(files, 0, files.Length, new FileSort()); string downloadFolder = ConfigurationManager.AppSettings["Host"]; if (!downloadFolder.EndsWith("/")) downloadFolder += "/"; downloadFolder += ConfigurationSettings.AppSettings["FolderDownload"]; if (!downloadFolder.EndsWith("/")) downloadFolder += "/"; if (files.Length > 0) { string fileName = ""; string linkFile = ""; string year = ""; string quy = ""; string ngaythang = ""; foreach (FileInfo file in files) { try { dr = tblFile.NewRow(); linkFile = downloadFolder + subFolder + "/" + file.Name; fileName = file.Name; dr["FileName"] = fileName; dr["LinkFile"] = ReturnLinkFile(file.Extension, linkFile); if (IsNumber(subFolder.Name)) { quy = ReturnTimeBCTC(file.Name); if (IsNumber(quy)) { year = "Q" + quy + "/" + subFolder.Name; dr["LoaiBaoCao"] = ReturnName(file.Name.Substring(0, file.Name.IndexOf(".")), quy, subFolder.Name); dr["Time"] = year; } else { string tempNT = ReturnTimeNQ(file.Name); if (tempNT != "") { ngaythang = tempNT + "-" + subFolder.Name; } else { ngaythang = subFolder.Name; } dr["Time"] = ngaythang; dr["LoaiBaoCao"] = ReturnName(file.Name.Substring(0, file.Name.IndexOf(".")), "", ngaythang); } } else { dr["LoaiBaoCao"] = ReturnName(file.Name.Substring(0, file.Name.IndexOf(".")), quy, subFolder.Name); } tblFile.Rows.Add(dr); } catch (Exception ex) { EventLog.WriteEntry("MemCached_DanhSachBCTC_GetFile", ex.InnerException.Message + ".\n" + ex.InnerException.StackTrace, EventLogEntryType.Error); } } } } tblFile.AcceptChanges(); } catch (Exception ex) { EventLog.WriteEntry("MemCached_DanhSachBCTC_", ex.InnerException.Message + ".\n" + ex.InnerException.StackTrace, EventLogEntryType.Error); } return tblFile; }
/// <summary> /// Lets say we have pictures and description.txt /// this will generate thmbs /// </summary> public void generateAlbum() { ///copy template dir to album dir var source = new DirectoryInfo(Program.template_path); source.CopyTo(album_path, true); var t_index = Path.Combine(album_path, "index.html"); var t_ShowPic = Path.Combine(album_path, "ShowPicture.html"); ///Create thumbnails //Console.WriteLine("Generating thmbs for " + album_dir.Name); CreateThmbs(); ///index.html //Console.WriteLine("Writing index for " + album_dir.Name); var index_content = File.ReadAllText(t_index); File.WriteAllText(Path.Combine(album_path,"index.html"), index_content.Replace("###pictures", ContentForIndex()) .Replace("###AlbumTitle", album_dir.Name) .Replace("###facebookThumnail", photos.First().Name) ); ///ShowPicture.html //Console.WriteLine("Writing ShowPicture....."); var showPicContent = File.ReadAllText(t_ShowPic); File.WriteAllText(Path.Combine(album_path, "ShowPicture.html"), showPicContent.Replace("###fotkae", GenDataForShowPicture())); }
public static OperationResults GoGalleryLive(int id) { lock (GetGallerySyncRoot(id)) { string livepath = GetGalleryLivePath(id); var dir = new DirectoryInfo(livepath); if (dir.Exists) { dir.Clear(); dir.Refresh(); } var gallery = BuildGalleryOutput(id); DirectoryInfo src = new DirectoryInfo(gallery.GetDevPath()); var content = gallery.LoadContent(false); ActionHandler<string, bool, bool> handler = content.SystemFilePathes == null || content.SystemFilePathes.Count == 0 ? (ActionHandler<string, bool, bool>)null : delegate(string path, bool isDir) { if (isDir) return true; return content.SystemFilePathes.FirstOrDefault(x => path.EndsWith(x)) == null; }; src.CopyTo(dir, handler); return OperationResults.Success; } }
public FileSystemInfoContract CopyItem(RootName root, FileSystemId source, string copyName, DirectoryId destination, bool recurse) { if (root == null) throw new ArgumentNullException(nameof(root)); if (source == null) throw new ArgumentNullException(nameof(source)); if (string.IsNullOrEmpty(copyName)) throw new ArgumentNullException(nameof(copyName)); if (destination == null) throw new ArgumentNullException(nameof(destination)); var effectivePath = GetFullPath(root, source.Value); var destinationPath = destination.Value; if (Path.IsPathRooted(destinationPath)) destinationPath = destinationPath.Remove(0, Path.GetPathRoot(destinationPath).Length); var effectiveCopyPath = GetFullPath(root, Path.Combine(destinationPath, copyName)); var directory = new DirectoryInfo(effectivePath); if (directory.Exists) { var directoryCopy = directory.CopyTo(effectiveCopyPath, recurse); return new DirectoryInfoContract(GetRelativePath(root, directoryCopy.FullName), directoryCopy.Name, directoryCopy.CreationTime, directoryCopy.LastWriteTime); } var file = new FileInfo(effectivePath); if (file.Exists) { var fileCopy = file.CopyTo(effectiveCopyPath); return new FileInfoContract(GetRelativePath(root, fileCopy.FullName), fileCopy.Name, fileCopy.CreationTime, fileCopy.LastWriteTime, fileCopy.Length, null); } throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Resource.PathNotFound, source.Value)); }
public void CopyDirectory() { var directory = ApplicationPaths.RootDirectory; var path1 = new DirectoryInfo(directory + @"\path\path"); path1.CreateRecursively(); CreateFoo(@"\path\path"); path1.CreateSubdirectory("path"); if (Directory.Exists(directory + @"\moved")) Directory.Delete(directory + @"\moved", true); path1.CopyTo(directory + @"\moved"); Assert.IsTrue(File.Exists(directory + @"\moved\foo.bar")); Assert.IsTrue(Directory.Exists(directory + @"\moved\path")); }