public void SafeDelete()
 {
     var dir = new DirectoryInfo("abc");
     dir.SafeDelete(true);
     dir.Refresh();
     Assert.That(dir.SafeDelete(true), Is.False);
     Directory.CreateDirectory(dir.GetDirectory("test2").FullName);
     dir.Refresh();
     Assert.That(dir.SafeDelete(true), Is.True);
     dir.Refresh();
     Assert.That(dir.Exists, Is.False);
 }
Example #2
0
        static void Main(string[] args)
        {
            //validate input arguements
            if(args.Length != 1)
                PrintUsageAndExit(FileErrors.FILE_DOES_NOT_EXIST);
            else
                inputFilename = args[0];

            //validate file type and that it exists
            FileInfo fInfo = new FileInfo(inputFilename);
            if(!fInfo.Exists)
                PrintUsageAndExit(FileErrors.FILE_DOES_NOT_EXIST);
            else if(!fInfo.Extension.Equals(".go"))
                PrintUsageAndExit(FileErrors.WRONG_FILETYPE);

            //read file
            string[] lines = File.ReadAllLines(inputFilename);

            GoLangFile gData = new GoLangFile(lines);

            DirectoryInfo dInfo = new DirectoryInfo(gData.PackageName);
            if(!dInfo.Exists)
            {
                dInfo.Create();
                dInfo.Refresh();
                if(!dInfo.Exists)
                {
                    Console.WriteLine("error: unable to create package folder");
                    Environment.Exit(-1);
                }
            }

            gData.ExportStructsAsClasses(dInfo, "CerebroM", NOV_HEADER);
        }
        /// <summary>
        /// Ensures that the data has been loaded in the Lucene index 
        /// 
        /// SIDE EFFECT
        /// This method sets property _searcher
        /// </summary>
        /// <param name="absoluteLucenePath">
        /// Absolute path of the directory where the Lucene files get stored.
        /// </param>
        /// <param name="onlyIfNotExists">
        /// If true, the index will only be created if there is no index at all (that is, no Lucene directory).
        /// If false, this will always create a new index.
        /// </param>
        /// <param name="loadLuceneIndex">
        /// Actually loads data into the Lucene index
        /// </param>
        protected void LoadStore(string absoluteLucenePath, bool onlyIfNotExists, Action<SimpleFSDirectory> loadLuceneIndex)
        {
            var luceneDir = new DirectoryInfo(absoluteLucenePath);
            bool luceneDirExists = luceneDir.Exists;

            if (!luceneDirExists)
            {
                luceneDir.Create();
                luceneDir.Refresh();
            }

            var directory = new SimpleFSDirectory(luceneDir);

            if (onlyIfNotExists && luceneDirExists)
            {
                // Make sure to always create a searcher.
                // There must actually be a valid Lucene index in the directory, otherwise this will throw an exception.
                _searcher = new IndexSearcher(directory, true);

                return;
            }

            loadLuceneIndex(directory);

            // Now that the index has been updated, need to open a new searcher.
            // Existing searcher will still be reading the previous index.

            _searcher = new IndexSearcher(directory, true);
        }
Example #4
0
        public void copyRemoteDirectoryLocal()
        {
            var info = util.GetUsernameAndPassword();
            using (var s = new SSHConnection(info.Item1, info.Item2))
            {
                // Create a "complex" directory structure on the remote machine
                s
                    .ExecuteCommand("mkdir -p /tmp/usergwatts/data")
                    .ExecuteCommand("mkdir -p /tmp/usergwatts/data/d1")
                    .ExecuteCommand("mkdir -p /tmp/usergwatts/data/d2")
                    .ExecuteCommand("echo hi1 > /tmp/usergwatts/data/f1")
                    .ExecuteCommand("echo hi2 > /tmp/usergwatts/data/d1/f2")
                    .ExecuteCommand("echo hi3 > /tmp/usergwatts/data/d2/f3")
                    .ExecuteCommand("echo hi4 > /tmp/usergwatts/data/d2/f4");

                // Remove everything local
                var d = new DirectoryInfo("./data");
                if (d.Exists)
                {
                    d.Delete(true);
                    d.Refresh();
                }
                d.Create();

                // Do the copy
                s.CopyRemoteDirectoryLocally("/tmp/usergwatts/data", d);

                Assert.IsTrue(File.Exists(Path.Combine(d.FullName, "f1")));
                Assert.IsTrue(File.Exists(Path.Combine(d.FullName, "d1", "f2")));
                Assert.IsTrue(File.Exists(Path.Combine(d.FullName, "d2", "f3")));
                Assert.IsTrue(File.Exists(Path.Combine(d.FullName, "d2", "f4")));
            }
        }
Example #5
0
        /// <summary>
        /// Initializes an area from a directory.
        /// </summary>
        public AreaState(ISystemContext context, DirectoryInfo directoryInfo) : base(null)
        {
            directoryInfo.Refresh();

            string name = directoryInfo.Name;
            
            // need to read the correct casing from the file system.
            if (directoryInfo.Exists)
            {
                DirectoryInfo[] directories = directoryInfo.Parent.GetDirectories(name);

                if (directories != null && directories.Length > 0)
                {
                    name = directories[0].Name;
                }
            }

            // get the system to use.
            FileSystemMonitor system = context.SystemHandle as FileSystemMonitor;

            if (system != null)
            {
                this.NodeId = system.CreateNodeIdFromDirectoryPath(ObjectTypes.AreaType, directoryInfo.FullName);
                this.BrowseName = new QualifiedName(name, system.NamespaceIndex);
                this.OnValidate = system.ValidateArea;
            }

            this.DisplayName = new LocalizedText(name);
            this.EventNotifier = EventNotifiers.None;
            this.TypeDefinitionId = GetDefaultTypeDefinitionId(context.NamespaceUris);
        }
Example #6
0
        /// <summary>
        /// Creates a file from a list of strings; each string is placed on a line in the file.
        /// </summary>
        /// <param name="TempFileName">Name of response file</param>
        /// <param name="Lines">List of lines to write to the response file</param>
        public static string Create(string TempFileName, List<string> Lines)
        {
            FileInfo TempFileInfo = new FileInfo( TempFileName );
            DirectoryInfo TempFolderInfo = new DirectoryInfo( TempFileInfo.DirectoryName );

            // Delete the existing file if it exists
            if( TempFileInfo.Exists )
            {
                TempFileInfo.IsReadOnly = false;
                TempFileInfo.Delete();
                TempFileInfo.Refresh();
            }

            // Create the folder if it doesn't exist
            if( !TempFolderInfo.Exists )
            {
                // Create the
                TempFolderInfo.Create();
                TempFolderInfo.Refresh();
            }

            using( FileStream Writer = TempFileInfo.OpenWrite() )
            {
                using( StreamWriter TextWriter = new StreamWriter( Writer ) )
                {
                    Lines.ForEach( x => TextWriter.WriteLine( x ) );
                }
            }

            return TempFileName;
        }
        public void TestReadWriteFileDirectory()
        {
            DirectoryInfo dir = new DirectoryInfo(@"c:\_junk\rwtesting");
             if (dir.Exists)
            dir.Delete(true);
             dir.Refresh();
             ReaderWriter rw = new ReaderWriter();

             Assert.IsFalse(rw.Exists(dir));
             rw.CreateDirectory(dir);
             Assert.IsTrue(rw.Exists(dir));

             string blah = "blah";
             string fileName = "blah.txt";

             FileInfo file = new FileInfo(Path.Combine(dir.FullName, fileName));
             Assert.IsFalse(rw.Exists(file));
             rw.WriteFile(file, blah.Encode());
             Assert.IsTrue(rw.Exists(file));
             byte[] buffer = rw.ReadFile(file);
             string result = buffer.Decode();
             Assert.AreEqual(blah, result);
             rw.Delete(file);
             Assert.IsFalse(file.Exists);
             rw.Delete(dir);
             Assert.IsFalse(dir.Exists);
        }
        public void AttemptToDownloadBadDS()
        {
            // Seen in wild: try to download a bad dataset, and it creates a directory
            // anyway. Ops!

            var dsinfo = MakeDSInfo("ds1.1.1");
            var d = new DirectoryInfo("AttemptToDownloadBadDS");
            if (d.Exists)
            {
                d.Delete(true);
            }

            var ld = new LinuxMirrorDownloaderPretend(d, "forkitover");
            var gf = new GRIDFetchToLinuxVisibleOnWindows(d, ld, "/bogus/files/store");

            try {
                var r = gf.GetDS(dsinfo);
            } catch (ArgumentException)
            {
                // Expecting it to throw here - no dataset should exist by that name!
            }

            // Did a local directory get created?
            d.Refresh();
            Assert.IsFalse(d.Exists);
        }
        public static IIndex LoadIndex(DirectoryInfo directory)
        {
            if (directory == null)
                throw new ArgumentNullException("directory", "directory cannot be null");
            directory.Refresh();
            if (!directory.Exists)
                throw new DirectoryNotFoundException(directory.FullName + " does not exist");
            FileInfo[] topLevelFiles = directory.GetFiles("*.*", SearchOption.TopDirectoryOnly);
            var toggleFile = topLevelFiles.FirstOrDefault(x => x.Name.Equals("toggle.txt", StringComparison.OrdinalIgnoreCase));
            var totalIndexHeaders = topLevelFiles.Count(x => x.Extension.Equals(".cfx", StringComparison.OrdinalIgnoreCase) || x.Extension.Equals(".cfs", StringComparison.OrdinalIgnoreCase));
            var segments = topLevelFiles.Count(x => x.Extension.Equals(".gen", StringComparison.OrdinalIgnoreCase));
            if (toggleFile == null) {
                // single
                if (segments == 0 && totalIndexHeaders == 0)
                    return new Index(directory) { IndexStructure = IndexType.None };
                return new Index(directory) { IndexStructure = IndexType.SingleIndex };
            }
            else {
                // double or cyclic
                DirectoryInfo mirrorDir = new DirectoryInfo(Path.Combine(directory.FullName, StaticValues.DirectoryMirror));
                DirectoryInfo dirA = new DirectoryInfo(Path.Combine(directory.FullName, StaticValues.DirectoryA));
                DirectoryInfo dirB = new DirectoryInfo(Path.Combine(directory.FullName, StaticValues.DirectoryB));

                if (!dirA.Exists || !dirB.Exists)
                    return new DoubleIndex(directory) { IndexStructure = IndexType.None };
                if (mirrorDir.Exists)
                    return new CyclicalIndex(directory);
                return new DoubleIndex(directory);
            }
        }
 public DirectoryInfo GetStorageDir(Guid newAct)
 {
     DirectoryInfo storageDir = new DirectoryInfo(GetStorageDir().FullName + Path.DirectorySeparatorChar + newAct.ToString());
     if (!storageDir.Exists)
         storageDir.Create();
     storageDir.Refresh();
     return storageDir;
 }
 public void Copying_To_Root_Directory_Should_Work()
 {
   targetDir = new DirectoryInfo(Path.Combine(rootDirectory.FullName, "targetFoo"));
   Assert.False(targetDir.Exists);
   var targetFolder = provider.CopyFolder(originalFolder, targetDir.FullName);
   targetDir.Refresh();
   Assert.True(targetDir.Exists);
 }
Example #12
0
 public DirectoryInfo GetAccountStorageDir(Guid accountId)
 {
     DirectoryInfo storageDir = new DirectoryInfo(StorageDir.FullName + Path.DirectorySeparatorChar + accountId.ToString());
     if (!storageDir.Exists)
         storageDir.Create();
     storageDir.Refresh();
     return storageDir;
 }
 public IgnoredCleanFileInfoEnumerator(DirectoryInfo directory)
 {
     directory.Refresh();
     if (!directory.Exists)
     {
         throw new DirectoryNotFoundException(string.Format("Directory '{0}' does not exist", directory));
     }
     _directory = directory;
 }
        public DirectoryFileBackup(FileInfo file, DirectoryInfo destination)
        {
            this.file = file;
            this.destination = destination;

            destination.Refresh();
            if(!destination.Exists)
                destination.Create();
        }
 public static void NewFolder(string s1)
 {
     var di = new DirectoryInfo(s1);
     if (di.Parent != null && !di.Exists)
         NewFolder(di.Parent.FullName);
     if (di.Exists) return;
     di.Create();
     di.Refresh();
 }
Example #16
0
        internal ResourceDirectory(DirectoryInfo directory)
        {
            directory.Refresh();

            foreach (var file in directory.EnumerateFiles("*.resx"))
            {
                var resourceFile = new ResourceFile(file);
                this.resourceByFileName[file.Name] = resourceFile;
            }
        }
Example #17
0
        public TestDirectory()
        {
            var tempPath = Path.GetTempPath();

            _testDir = new DirectoryInfo(Path.Combine(tempPath, Guid.NewGuid().ToString()));
            Assume.That(_testDir.Exists, Is.False, _testDir + " should not already exist");

            _testDir.Create();
            _testDir.Refresh();
            Assume.That(_testDir.Exists, Is.True, "Failed to create test dir " + _testDir);
        }
Example #18
0
        public static void EnsureDirectoryExists(DirectoryInfo directory)
        {
            directory.Refresh();
            if (directory.Exists)
            {
                return;
            }

            EnsureDirectoryExists(directory.Parent);

            directory.Create();
        }
Example #19
0
 /// <summary>
 /// Checks if the provided DirectoryInfo path exists.
 /// </summary>
 /// <param name="dInfo">Directory to check</param>
 /// <returns>True if the directory exists, false if it doesn't or the DirectoryInfo is null</returns>
 public static bool DirectoryExists(System.IO.DirectoryInfo dInfo)
 {
     if (dInfo != null)
     {
         dInfo.Refresh();
         return(dInfo.Exists);
     }
     else
     {
         return(false);
     }
 }
Example #20
0
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            // Caminho que iniciou o .EXE
            var currentDir = Environment.CurrentDirectory;

            // Caminho garantido do .EXE
            var pathDoExe = AppDomain.CurrentDomain.BaseDirectory;

            var pathCompleto = Path.Combine(pathDoExe, "readme.txt");

            File.WriteAllText(pathCompleto, txtConteudo.Text);

            var ioPath = Path.Combine(pathDoExe, "Teste", "IO");

            // Directory.CreateDirectory(ioPath);

            var ioDir = new DirectoryInfo(ioPath);

            ioDir.Refresh();

            if (!ioDir.Exists)
            {
                ioDir.Create();
            }

            FileInfo[] todosArquivos = ioDir.GetFiles();

            int i = 0;

            foreach (FileInfo arquivo in todosArquivos)
            {
                var nomeSemExtensao = Path.
                    GetFileNameWithoutExtension(arquivo.FullName);

                int numeroArquivo;

                if (int.TryParse(nomeSemExtensao, out numeroArquivo))
                {
                    i = Math.Max(i, numeroArquivo);
                }
            }

            var limite = i + 100;

            for (; i <  limite; i++)
            {
                using (var fileStream = File.Create(Path.Combine(ioPath, i + ".txt")))
                using (var streamWriter = new StreamWriter(fileStream))
                {
                    streamWriter.Write(txtConteudo.Text);
                }
            }
        }
 internal DirectoryInfo getObjectsDirectory()
 {
     // Create the 'objects' subdirectory if it doesn't exist:
     DirectoryInfo objDir = new DirectoryInfo(System.IO.Path.Combine(Root.FullName, "objects"));
     if (!objDir.Exists)
         lock (SystemLock)
         {
             objDir.Refresh();
             if (!objDir.Exists)
                 objDir.Create();
         }
     return objDir;
 }
Example #22
0
 static void Tidy(DirectoryInfo tree)
 {
     foreach (DirectoryInfo di in tree.EnumerateDirectories())
     {
         Tidy(di);
     }
     tree.Refresh();
     if (!tree.EnumerateFileSystemInfos().Any())
     {
         tree.Delete();
     }
     return;
 }
Example #23
0
        public static void WaitExistImage(string pathFolder)
        {
            var fi      = new System.IO.DirectoryInfo(pathFolder);
            int seconds = 0;

            if (fi.Exists)
            {
                fi.Refresh();
                while (fi.GetFiles().Count() == 0)
                {
                    System.Threading.Thread.Sleep(1000);

                    fi.Refresh();

                    seconds++;
                    if (seconds == 60)
                    {
                        return;
                    }
                }
            }
        }
Example #24
0
        public void DirectoryInfoExists()
        {
            string dirPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            Directory.CreateDirectory(dirPath);

            var dir = new DirectoryInfo(dirPath);
            Assert.IsTrue(dir.Exists, "Directory does not exist.");

            Directory.Delete(dirPath);

            dir.Refresh();
            AssertHelper.IgnoreOn(AssertedPlatform.Mono, () => { var doesExist = dir.Exists; }, "As identified by nestalk (http://bugzilla.novell.com/show_bug.cgi?id=582667), DirectoryInfo.Refresh() doesn't seem to refresh the Exist property.");
            Assert.IsFalse(dir.Exists, "Directory exists.");
        }
Example #25
0
        public static void ebfFolderCreate(Object s1)
        {
            DirectoryInfo di = new DirectoryInfo(s1.ToString());
            if (di.Parent != null && !di.Exists)
            {
                ebfFolderCreate(di.Parent.FullName);
            }

            if (!di.Exists)
            {
                di.Create();
                di.Refresh();
            }
        }
        public FileSystemLearningRepository(DirectoryInfo input)
        {
            _rootDirectory = input;
            if(!input.Exists)
            {
                input.Create();
                input.Refresh();
            }

            var dirs = input.EnumerateDirectories("??");
            _learnings = dirs
                .SelectMany(d =>d.EnumerateFiles().Select(f => new {f.Name, Text = File.ReadAllText(f.FullName).Trim().Split('\n').ToList()}))
                .ToDictionary(t => t.Name, t => t.Text);
        }
Example #27
0
 /// <summary>
 /// Gets information about all existing backups
 /// </summary>
 /// <returns> List of SnapshotInfo</returns>
 public List<SnapshotInfo> GetAllInfo()
 {
     DirectoryInfo info = new DirectoryInfo(Path);
     info.Refresh();
     string[] files = info.GetFiles("*.xml")
         .Select(inf => inf.FullName).ToArray();
     var result = new List<SnapshotInfo>();
     foreach (string path in files)
     {
         XDocument doc = XDocument.Load(path);
         SnapshotInfo snapshot = Serializer.ParseInfo(doc);
         result.Add(snapshot);
     }
     return result;
 }
 public void Clear()
 {
     var dir = new DirectoryInfo("abc");
     var subdir = dir.GetDirectory("test2");
     subdir.Create();
     using (var fs = new FileStream(subdir.GetFile("test3.txt").FullName, FileMode.Create)) {
         fs.WriteByte(1);
     }
     dir.Clear();
     Assert.That(dir.Exists, Is.True);
     Assert.That(dir.SafeClear(), Is.True);
     Assert.That(dir.SafeDelete(), Is.True);
     dir.Refresh();
     Assert.That(dir.Exists, Is.False);
     Assert.That(dir.SafeClear(), Is.False);
 }
Example #29
0
 public void copyBadRemoteDirectoryLocal()
 {
     var info = util.GetUsernameAndPassword();
     using (var s = new SSHConnection(info.Item1, info.Item2))
     {
         // Do the copy
         var d = new DirectoryInfo("./databogus");
         if (d.Exists)
         {
             d.Delete(true);
             d.Refresh();
         }
         d.Create();
         s.CopyRemoteDirectoryLocally("/tmp/usergwatts/databogusbogusbogusbogus", d);
     }
 }
Example #30
0
 /// <summary>
 /// Extracts a directory entry from the specified stream.
 /// </summary>
 /// <param name="inputStream">The <see cref="Stream" /> containing the directory entry.</param>
 /// <param name="destDirectory">The directory where to create the subdirectory.</param>
 /// <param name="entryName">The name of the directory entry.</param>
 /// <param name="entryDate">The date of the entry.</param>
 /// <exception cref="BuildException">
 ///   <para>The destination directory for the entry could not be created.</para>
 /// </exception>
 protected void ExtractDirectory(Stream inputStream, string destDirectory, string entryName, DateTime entryDate)
 {
     DirectoryInfo destDir = new DirectoryInfo(Path.Combine(
         destDirectory, entryName));
     if (!destDir.Exists) {
         try {
             destDir.Create();
             destDir.LastWriteTime = entryDate;
             destDir.Refresh();
         } catch (Exception ex) {
             throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                 "Directory '{0}' could not be created.", destDir.FullName),
                 Location, ex);
         }
     }
 }
Example #31
0
        /// <summary>
        /// Initialisiert statische Felder.
        /// </summary>
        static TestBase()
        {
            // Load from configuration
            TestDirectory = new DirectoryInfo( ConfigurationManager.AppSettings["TestDirectory"] );
            Profile = ProfileManager.FindProfile( ConfigurationManager.AppSettings["ProfileName"] );

            // Create
            if (!TestDirectory.Exists)
            {
                // Do it
                TestDirectory.Create();

                // Must manually refresh
                TestDirectory.Refresh();
            }
        }
Example #32
0
 public void EnsureDirectoryStructure(Guid accountId, string path, DirectoryInfo baseDir)
 {
     path = path.Replace(Path.GetFileName(path), string.Empty);
     string[] parts = path.Split(Path.DirectorySeparatorChar);
     DirectoryInfo dir = baseDir;
     foreach (string part in parts)
     {
         DirectoryInfo sub = new DirectoryInfo(dir.FullName + Path.DirectorySeparatorChar + part);
         if (!sub.Exists)
         {
             sub.Create();
             sub.Refresh();
         }
         dir = sub;
     }
 }
Example #33
0
    /// <summary>
    /// Create a folder at the specified path.
    /// </summary>
    /// <param name="dInfo"></param>
    /// <returns></returns>
    public static bool CreateFolder(System.IO.DirectoryInfo dInfo)
    {
        // TODO: Create parent directories if they don't exist
        bool folderCreated = false;

        if (dInfo != null)
        {
            if (!dInfo.Exists)
            {
                dInfo.Create();
                dInfo.Refresh();
                folderCreated = dInfo.Exists;
                Console.WriteLine(folderCreated ? "INFO: Util: Creating folder: " : "INFO: Util: Failed to create folder: " + dInfo.FullName);
            }
        }
        return(folderCreated);
    }
Example #34
0
        /// <summary>
        /// Tries to set the attributes.
        /// </summary>
        /// <param name="This">This DirectoryInfo.</param>
        /// <param name="attributes">The attributes.</param>
        /// <returns><c>true</c> on success; otherwise, <c>false</c>.</returns>
        public static bool TrySetAttributes(this DirectoryInfo This, FileAttributes attributes)
        {
#if NET40
            Contract.Requires(This != null);
#endif
            This.Refresh();

            if (!This.Exists)
            {
                return(false);
            }

            if (This.Attributes == attributes)
            {
                return(true);
            }

            try {
                This.Attributes = attributes;
                return(true);
            } catch (Exception) {
                return(This.Attributes == attributes);
            }
        }
Example #35
0
        /// <summary>
        /// Tries to set the creation time.
        /// </summary>
        /// <param name="This">This DirectoryInfo.</param>
        /// <param name="creationTimeUtc">The date&amp;time.</param>
        /// <returns><c>true</c> on success; otherwise, <c>false</c>.</returns>
        public static bool TrySetCreationTimeUtc(this DirectoryInfo This, DateTime creationTimeUtc)
        {
#if NET40
            Contract.Requires(This != null);
#endif
            This.Refresh();

            if (!This.Exists)
            {
                return(false);
            }

            if (This.CreationTimeUtc == creationTimeUtc)
            {
                return(true);
            }

            try {
                This.CreationTimeUtc = creationTimeUtc;
                return(true);
            } catch (Exception) {
                return(This.CreationTimeUtc == creationTimeUtc);
            }
        }