Exemplo n.º 1
0
        public static void Move(string sourceDirName, string destDirName)
        {
            if (Path.GetPathRoot(sourceDirName) != Path.GetPathRoot(destDirName))
            {
                throw new ArgumentException();
            }

            // sourceDirName and destDirName validation in Path.GetFullPath()

            sourceDirName = Path.GetFullPath(sourceDirName);
            destDirName   = Path.GetFullPath(destDirName);

            var tryCopyAndDelete = false;
            var srcRecord        = FileSystemManager.AddToOpenList(sourceDirName);

            try {
                // Make sure sourceDir is actually a directory
                if (!Exists(sourceDirName))
                {
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.DirectoryNotFound);
                }

                // If Move() returns false, we'll try doing copy and delete to accomplish the move
                tryCopyAndDelete = !DriveInfo.GetForPath(sourceDirName).Move(sourceDirName, destDirName);
            }
            finally {
                FileSystemManager.RemoveFromOpenList(srcRecord);
            }

            if (tryCopyAndDelete)
            {
                RecursiveCopyAndDelete(sourceDirName, destDirName);
            }
        }
Exemplo n.º 2
0
        public FileEnum(string path, FileEnumFlags flags)
        {
            this.m_flags = flags;
            this.m_path  = path;

            this.m_openForReadHandle = FileSystemManager.AddToOpenListForRead(this.m_path);
            this.m_findFile          = DriveInfo.GetForPath(this.m_path).Find(this.m_path, "*");
        }
Exemplo n.º 3
0
        public static DirectoryInfo CreateDirectory(string path)
        {
            // path validation in Path.GetFullPath()

            path = Path.GetFullPath(path);

            /// According to MSDN, Directory.CreateDirectory on an existing
            /// directory is no-op.
            DriveInfo.GetForPath(path).CreateDirectory(path);

            return(new DirectoryInfo(path));
        }
Exemplo n.º 4
0
        public static void Delete(string path, bool recursive)
        {
            path = Path.GetFullPath(path);

            var record = FileSystemManager.LockDirectory(path);
            var drive  = DriveInfo.GetForPath(path);

            try {
                var attributes = drive.GetAttributes(path);

                if ((uint)attributes == 0xFFFFFFFF)
                {
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.DirectoryNotFound);
                }

                if (((attributes & (FileAttributes.Directory)) == 0) ||
                    ((attributes & (FileAttributes.ReadOnly)) != 0))
                {
                    /// it's readonly or not a directory
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.UnauthorizedAccess);
                }

                if (!Exists(path)) // make sure it is indeed a directory (and not a file)
                {
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.DirectoryNotFound);
                }

                if (!recursive)
                {
                    var ff = drive.Find(path, "*");

                    try {
                        if (ff.GetNext() != null)
                        {
                            throw new IOException("", (int)IOException.IOExceptionErrorCode.DirectoryNotEmpty);
                        }
                    }
                    finally {
                        ff.Close();
                    }
                }

                drive.Delete(path);
            }
            finally {
                // regardless of what happened, we need to release the directory when we're done
                FileSystemManager.UnlockDirectory(record);
            }
        }
Exemplo n.º 5
0
        private static void RecursiveCopyAndDelete(string sourceDirName, string destDirName)
        {
            string[] files;
            int      filesCount, i;
            var      relativePathIndex = sourceDirName.Length + 1; // relative path starts after the sourceDirName and a path seperator
            // We have to make sure no one else can modify it (for example, delete the directory and
            // create a file of the same name) while we're moving
            var recordSrc = FileSystemManager.AddToOpenList(sourceDirName);

            try {
                // Make sure sourceDir is actually a directory
                if (!Exists(sourceDirName))
                {
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.DirectoryNotFound);
                }

                // Make sure destDir does not yet exist
                if (Exists(destDirName))
                {
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.PathAlreadyExists);
                }

                DriveInfo.GetForPath(destDirName).CreateDirectory(destDirName);

                files      = Directory.GetFiles(sourceDirName);
                filesCount = files.Length;

                for (i = 0; i < filesCount; i++)
                {
                    File.Copy(files[i], Path.Combine(destDirName, files[i].Substring(relativePathIndex)), false, true);
                }

                files      = Directory.GetDirectories(sourceDirName);
                filesCount = files.Length;

                for (i = 0; i < filesCount; i++)
                {
                    RecursiveCopyAndDelete(files[i], Path.Combine(destDirName, files[i].Substring(relativePathIndex)));
                }

                DriveInfo.GetForPath(sourceDirName).Delete(sourceDirName);
            }
            finally {
                FileSystemManager.RemoveFromOpenList(recordSrc);
            }
        }
Exemplo n.º 6
0
        public void Reset()
        {
            if (this.m_disposed)
            {
                throw new ObjectDisposedException();
            }

            if (this.m_findFile != null)
            {
                this.m_findFile.Close();
            }

            if (this.m_openForReadHandle == null)
            {
                this.m_openForReadHandle = FileSystemManager.AddToOpenListForRead(this.m_path);
            }

            this.m_findFile = DriveInfo.GetForPath(this.m_path).Find(this.m_path, "*");
        }
Exemplo n.º 7
0
        public void Refresh()
        {
            var record = FileSystemManager.AddToOpenListForRead(this.m_fullPath);

            try
            {
                this._nativeFileInfo = DriveInfo.GetForPath(this.m_fullPath).GetFileSystemEntry(this.m_fullPath);

                if (this._nativeFileInfo == null)
                {
                    var errorCode = (this is FileInfo) ? IOException.IOExceptionErrorCode.FileNotFound : IOException.IOExceptionErrorCode.DirectoryNotFound;
                    throw new IOException("", (int)errorCode);
                }
            }
            finally
            {
                FileSystemManager.RemoveFromOpenList(record);
            }
        }
Exemplo n.º 8
0
        public static bool Exists(string path)
        {
            // path validation in Path.GetFullPath()

            path = Path.GetFullPath(path);

            /// Is this the absolute root? this always exists.
            if (path.Length == 3 && path[0] >= 'A' && path[0] <= 'Z' && path[1] == ':' && (path[2] == Path.DirectorySeparatorChar))
            {
                return(true);
            }
            else
            {
                try {
                    var attributes = DriveInfo.GetForPath(path).GetAttributes(path);

                    /// This is essentially file not found.
                    if ((uint)attributes == 0xFFFFFFFF)
                    {
                        return(false);
                    }

                    /// Need to make sure these are not FAT16 or FAT32 specific.
                    if ((((FileAttributes)attributes) & FileAttributes.Directory) == FileAttributes.Directory)
                    {
                        /// It is a directory.
                        return(true);
                    }
                }
                catch (Exception) {
                    return(false);
                }
            }

            return(false);
        }
Exemplo n.º 9
0
        public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
        {
            // This will perform validation on path
            this._fileName = Path.GetFullPath(path);

            // make sure mode, access, and share are within range
            if (mode < FileMode.CreateNew || mode > FileMode.Append ||
                access < FileAccess.Read || access > FileAccess.ReadWrite ||
                share < FileShare.None || share > FileShare.ReadWrite)
            {
                throw new ArgumentOutOfRangeException();
            }

            // Get wantsRead and wantsWrite from access, note that they cannot both be false
            this.wantsRead  = (access & FileAccess.Read) == FileAccess.Read;
            this.wantsWrite = (access & FileAccess.Write) == FileAccess.Write;

            // You can't open for readonly access (wantsWrite == false) when
            // mode is CreateNew, Create, Truncate or Append (when it's not Open or OpenOrCreate)
            if (mode != FileMode.Open && mode != FileMode.OpenOrCreate && !this.wantsWrite)
            {
                throw new ArgumentException();
            }

            // We need to register the share information prior to the actual file open call (the NativeFileStream ctor)
            // so subsequent file operation on the same file will behave correctly
            this._fileRecord = FileSystemManager.AddToOpenList(this._fileName, (int)access, (int)share);

            try {
                this.drive = DriveInfo.GetForPath(this._fileName);
                var attributes = this.drive.GetAttributes(this._fileName);
                var exists     = ((uint)attributes != 0xFFFFFFFF);
                this.isReadOnly = (exists) ? (((FileAttributes)attributes) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly : false;

                // If the path specified is an existing directory, fail
                if (exists && ((((FileAttributes)attributes) & FileAttributes.Directory) == FileAttributes.Directory))
                {
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.UnauthorizedAccess);
                }

                // The seek limit is 0 (the beginning of the file) for all modes except Append
                this._seekLimit = 0;


                switch (mode)
                {
                case FileMode.CreateNew:     // if the file exists, IOException is thrown
                    if (exists)
                    {
                        throw new IOException("", (int)IOException.IOExceptionErrorCode.PathAlreadyExists);
                    }
                    this._nativeFileStream = this.drive.OpenFile(this._fileName, bufferSize);
                    break;

                case FileMode.Create:     // if the file exists, it should be overwritten
                    this._nativeFileStream = this.drive.OpenFile(this._fileName, bufferSize);
                    if (exists)
                    {
                        this._nativeFileStream.Length = 0;
                    }
                    break;

                case FileMode.Open:     // if the file does not exist, IOException/FileNotFound is thrown
                    if (!exists)
                    {
                        throw new IOException("", (int)IOException.IOExceptionErrorCode.FileNotFound);
                    }
                    this._nativeFileStream = this.drive.OpenFile(this._fileName, bufferSize);
                    break;

                case FileMode.OpenOrCreate:     // if the file does not exist, it is created
                    this._nativeFileStream = this.drive.OpenFile(this._fileName, bufferSize);
                    break;

                case FileMode.Truncate:     // the file would be overwritten. if the file does not exist, IOException/FileNotFound is thrown
                    if (!exists)
                    {
                        throw new IOException("", (int)IOException.IOExceptionErrorCode.FileNotFound);
                    }
                    this._nativeFileStream        = this.drive.OpenFile(this._fileName, bufferSize);
                    this._nativeFileStream.Length = 0;
                    break;

                case FileMode.Append:     // Opens the file if it exists and seeks to the end of the file. Append can only be used in conjunction with FileAccess.Write
                    // Attempting to seek to a position before the end of the file will throw an IOException and any attempt to read fails and throws an NotSupportedException
                    if (access != FileAccess.Write)
                    {
                        throw new ArgumentException();
                    }
                    this._nativeFileStream = this.drive.OpenFile(this._fileName, bufferSize);
                    this._seekLimit        = this._nativeFileStream.Seek(0, SeekOrigin.End);
                    break;

                    // We've already checked the mode value previously, so no need for default
                    //default:
                    //    throw new ArgumentOutOfRangeException();
                }

                // Now that we have a valid NativeFileStream, we add it to the FileRecord, so it could gets clean up
                // in case an eject or force format
                this._fileRecord.NativeFileStream = this._nativeFileStream;

                // Make sure the requests (wantsRead / wantsWrite) matches the filesystem capabilities (canRead / canWrite)
                if ((this.wantsRead && !this.CanRead) || (this.wantsWrite && !this.CanWrite))
                {
                    throw new IOException("", (int)IOException.IOExceptionErrorCode.UnauthorizedAccess);
                }
            }
            catch {
                // something went wrong, clean up and re-throw the exception
                if (this._nativeFileStream != null)
                {
                    this._nativeFileStream.Close();
                }

                FileSystemManager.RemoveFromOpenList(this._fileRecord);

                throw;
            }
        }
Exemplo n.º 10
0
        private static string[] GetChildren(string path, string searchPattern, bool isDirectory)
        {
            // path and searchPattern validation in Path.GetFullPath() and Path.NormalizePath()

            path = Path.GetFullPath(path);

            if (!Directory.Exists(path))
            {
                throw new IOException("", (int)IOException.IOExceptionErrorCode.DirectoryNotFound);
            }

            Path.NormalizePath(searchPattern, true);

            var fileNames = new ArrayList();

            var root = Path.GetPathRoot(path);

            if (false && string.Equals(root, path))   //TODO check to see it always go here
            /// This is special case. Return all the volumes.
            /// Note this will not work, once we start having \\server\share like paths.

            {
                if (isDirectory)
                {
                    var volumes = DriveInfo.GetDrives();
                    var count   = volumes.Length;
                    for (var i = 0; i < count; i++)
                    {
                        fileNames.Add(volumes[i].RootDirectory.Name);
                    }
                }
            }
            else
            {
                var record = FileSystemManager.AddToOpenListForRead(path);
                IFileSystemEntryFinder ff = null;
                try {
                    ff = DriveInfo.GetForPath(path).Find(path, searchPattern);

                    var targetAttribute = (isDirectory ? FileAttributes.Directory : 0);

                    var fileinfo = ff.GetNext();

                    while (fileinfo != null)
                    {
                        if ((fileinfo.Attributes & FileAttributes.Directory) == targetAttribute)
                        {
                            fileNames.Add(fileinfo.FileName);
                        }

                        fileinfo = ff.GetNext();
                    }
                }
                finally {
                    if (ff != null)
                    {
                        ff.Close();
                    }
                    FileSystemManager.RemoveFromOpenList(record);
                }
            }

            return((string[])fileNames.ToArray(typeof(string)));
        }