GetPathRoot() public static method

public static GetPathRoot ( string path ) : string
path string
return string
        /// <summary>
        /// 用路徑抓出使用者電腦容量
        /// </summary>
        /// <param name="Drive">路徑</param>
        /// <returns></returns>
        bool RemainingSpace(string Drive)
        {
            try
            {
                if (Directory.Exists(Drive) == false)
                {
                    Directory.CreateDirectory(Drive);
                }

                string str     = Path.GetPathRoot(Drive);
                bool   success = GetDiskFreeSpaceEx(Path.GetPathRoot(Drive), out ulong FreeBytesAvailable, out ulong TotalNumberOfBytes, out ulong TotalNumberOfFreeBytes);

                if (!success)
                {
                    Inteware_Messagebox Msg = new Inteware_Messagebox();
                    Msg.ShowMessage(TranslationSource.Instance["CannnotGetRemainingSpace"]);
                    return(false);
                }

                label_AvailableSpace.Tag     = TotalNumberOfFreeBytes;
                label_AvailableSpace.Content = ConvertDiskUnit(TotalNumberOfFreeBytes, (int)_diskUnit.MB);
                return(true);
            }
            catch (Exception ex)
            {
                Inteware_Messagebox Msg = new Inteware_Messagebox();
                Msg.ShowMessage(ex.Message);
                return(false);
            }
        }
Beispiel #2
0
        public Updater()
        {
            //init files address
            switch (Properties.Settings.Default.ReleaseType)
            {
            case "dev":
                _vstoAddress             = Properties.Settings.Default.DevAddr + CommonText.VstoName;
                _offlineInstallerAddress = Properties.Settings.Default.DevAddr + CommonText.InstallerName;
                break;

            case "release":
                _vstoAddress             = Properties.Settings.Default.ReleaseAddr + CommonText.VstoName;
                _offlineInstallerAddress = Properties.Settings.Default.ReleaseAddr + CommonText.InstallerName;
                break;

            default:
                _vstoAddress             = "";
                _offlineInstallerAddress = "";
                break;
            }

            // handle special char case for EURO user
            _targetInstallFolder = Path.Combine(
                (IsSpecialCharPresentInInstallPath()
                    ? Path.GetPathRoot(Environment.SystemDirectory)
                    : Path.GetTempPath()),
                @"PowerPointLabsInstaller");
        }
Beispiel #3
0
        private string ExportImages(Book book, string outputPath)
        {
            var bookDir = Path.Combine(outputPath, book.BookName.ToSafeFilename());

            try
            {
                bookDir.EnsureEmptyDirectory();

                _logger.Log($"Saving book pages in folder {bookDir}");

                foreach (var page in book.Pages.OrderBy(p => p.PageIndex))
                {
                    File.Move(page.PageImagePath, Path.Combine(bookDir, page.FileName));
                }

                Path.GetPathRoot(book.Pages.First().PageImagePath)?.TryDeleteDirectory();

                Path.GetDirectoryName(book.Pages.First().PageImagePath).TryDeleteDirectory();

                _logger.Log($"Book pages saved in folder {bookDir}");

                return(bookDir);
            }
            catch (Exception ex)
            {
                _logger.Log(ex.Message);
                _logger.Log(ex.StackTrace);
                _logger.Log($"Error: Unable to copy pages to book folder. Pages were downloaded in {Path.GetDirectoryName(book.Pages.First().PageImagePath)}");

                return(null);
            }
        }
        void GetRouteAndBasePath(string file, out string routePath, out string basePath)
        {
            routePath = null;
            basePath  = null;
            Stack <string> subDirectories = new Stack <string>();
            string         directory      = Path.GetDirectoryName(file);
            var            root           = Path.GetPathRoot(file);

            while (directory.Length > root.Length)
            {
                string subdDirectoryName = Path.GetFileName(directory);
                if (subdDirectoryName.ToLowerInvariant().Equals("routes"))
                {
                    routePath = Path.Combine(directory, subDirectories.Pop());
                    basePath  = Path.GetDirectoryName(Path.GetDirectoryName(routePath));
                    return;
                }
                if (subdDirectoryName.ToLowerInvariant().Equals("trains"))
                {
                    basePath = Path.GetDirectoryName(directory);
                    return;
                }
                if (subdDirectoryName.ToLowerInvariant().Equals("trains"))
                {
                    basePath = Path.GetDirectoryName(directory);
                }
                if (subdDirectoryName.ToLowerInvariant().Equals("sound"))
                {
                    basePath = Path.GetDirectoryName(directory);
                }
                subDirectories.Push(Path.GetFileName(directory));
                directory = Path.GetDirectoryName(directory);
            }
        }
Beispiel #5
0
        private static void MoveApp()
        {
            Apath = (Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
            FPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)) + "ModAPI";

            //Now Create all of the directories
            foreach (string dirPath in Directory.GetDirectories(Apath, "*",
                                                                SearchOption.AllDirectories))
            {
                Directory.CreateDirectory(dirPath.Replace(Apath, FPath));
            }

            //Copy all the files & Replaces any files with the same name
            foreach (string newPath in Directory.GetFiles(Apath, "*.*",
                                                          SearchOption.AllDirectories))
            {
                File.Copy(newPath, newPath.Replace(Apath, FPath), true);
            }
            CDSK();
        }
Beispiel #6
0
        private void loadFolder(string folder)
        {
            current_folder = folder;

            // Draw folder nav buttons
            folderNavPanel.Children.Clear();
            string root = Path.GetPathRoot(folder);
            Button rbtn = new Button();

            rbtn.Tag     = root;
            rbtn.Content = root;
            rbtn.Click  += folderNavClick;
            folderNavPanel.Children.Add(rbtn);
            if (root != folder)
            {
                string   partial_path = root;
                string[] path_parts   = current_folder.Remove(0, root.Length).Split("\\");
                foreach (string f in path_parts)
                {
                    partial_path += (f);
                    Button btn = new Button();
                    btn.Padding = new Thickness(5);
                    btn.Tag     = partial_path;
                    btn.Content = f + " \\";
                    btn.Click  += folderNavClick;
                    folderNavPanel.Children.Add(btn);
                    partial_path += "\\";
                }
            }

            // load left panel images
            filePanel.Children.Clear();
            foreach (string folderName in Directory.GetDirectories(current_folder))
            {
                DirectoryInfo directory_info = new DirectoryInfo(folderName);
                if (directory_info.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    continue;
                }
                Tile folderTile = new Tile();
                folderTile.tileType          = Tile.Type.Folder;
                folderTile.fullPath          = folderName;
                folderTile.Caption.Text      = Path.GetFileName(folderName);
                folderTile.Thumbnail.Source  = ThumbnailFromUri(new Uri(@"pack://application:,,,/Resources/folder.jpg", UriKind.Absolute));
                folderTile.Thumbnail.Height  = 75;
                folderTile.MouseDoubleClick += folderClick;
                filePanel.Children.Add(folderTile);
            }
            current_image_tiles.Clear();
            current_file_index = -1;
            foreach (String fname in Directory.GetFiles(current_folder))
            {
                if (image_extensions.IndexOf(Path.GetExtension(fname).ToLower()) > 0)
                {
                    Tile imageTile = new Tile();
                    imageTile.tileType           = Tile.Type.Image;
                    imageTile.fullPath           = fname;
                    imageTile.Caption.Text       = Path.GetFileName(fname);
                    imageTile.MouseLeftButtonUp += thumbnailButtonClick;
                    imageTile.MouseDoubleClick  += thumbnailDoubleClick;
                    filePanel.Children.Add(imageTile);
                    current_image_tiles.Add(imageTile);
                }
            }
            if (current_image_tiles.Count > 0)
            {
                loadThumbsInBackground(current_image_tiles[0]);
                selectTile(current_image_tiles[0]);
            }
            else
            {
                previewImage.Source = null;
            }

            updateNavButtons();
            filePanelScrollViewer.ScrollToVerticalOffset(0);
        }
 public DriveInfo GetDrive()
 {
     return(new DriveInfo(Path.GetPathRoot(GetBasePath())));
 }
Beispiel #8
0
        /// <include file='doc\Directory.uex' path='docs/doc[@for="Directory.Move"]/*' />
        public static void Move(String sourceDirName, String destDirName)
        {
            if (sourceDirName == null)
            {
                throw new ArgumentNullException("sourceDirName");
            }
            if (sourceDirName.Length == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceDirName");
            }

            if (destDirName == null)
            {
                throw new ArgumentNullException("destDirName");
            }
            if (destDirName.Length == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName");
            }

            String fullsourceDirName = Path.GetFullPathInternal(sourceDirName);

            new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { fullsourceDirName }, false, false).Demand();

            String fulldestDirName = Path.GetFullPathInternal(destDirName);

            new FileIOPermission(FileIOPermissionAccess.Write, new String[] { fulldestDirName }, false, false).Demand();

            String sourcePath;

            if (fullsourceDirName.EndsWith('\\'))
            {
                sourcePath = fullsourceDirName;
            }
            else
            {
                sourcePath = fullsourceDirName + "\\";
            }

            String destPath;

            if (fulldestDirName.EndsWith('\\'))
            {
                destPath = fulldestDirName;
            }
            else
            {
                destPath = fulldestDirName + "\\";
            }

            if (CultureInfo.InvariantCulture.CompareInfo.Compare(sourcePath, destPath, CompareOptions.IgnoreCase) == 0)
            {
                throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent"));
            }

            String sourceRoot      = Path.GetPathRoot(sourcePath);
            String destinationRoot = Path.GetPathRoot(destPath);

            if (CultureInfo.InvariantCulture.CompareInfo.Compare(sourceRoot, destinationRoot, CompareOptions.IgnoreCase) != 0)
            {
                throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot"));
            }

            if (!Directory.InternalExists(Path.GetPathRoot(fulldestDirName))) // Win9x hack to behave same as Winnt.
            {
                throw new DirectoryNotFoundException(String.Format(Environment.GetResourceString("IO.PathNotFound_Path"), destDirName));
            }

            if (!Win32Native.MoveFile(sourceDirName, destDirName))
            {
                int hr = Marshal.GetLastWin32Error();
                if (hr == Win32Native.ERROR_FILE_NOT_FOUND)                 // Win32 is weird, it gives back a file not found
                {
                    hr = Win32Native.ERROR_PATH_NOT_FOUND;
                    __Error.WinIOError(hr, sourceDirName);
                }
                if (hr == Win32Native.ERROR_ACCESS_DENIED) // WinNT throws IOException. Win9x hack to do the same.
                {
                    throw new IOException(String.Format(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path"), sourceDirName));
                }
                __Error.WinIOError(hr, String.Empty);
            }
        }
Beispiel #9
0
        static string CanonicalizePath(string path)
        {
            // STEP 1: Check for empty string
            if (path == null)
            {
                return(path);
            }
            if (Environment.IsRunningOnWindows)
            {
                path = path.Trim();
            }

            if (path.Length == 0)
            {
                return(path);
            }

            // STEP 2: Check to see if this is only a root
            string root = Path.GetPathRoot(path);

            // it will return '\' for path '\', while it should return 'c:\' or so.
            // Note: commenting this out makes the need for the (target == 1...) check in step 5
            //if (root == path) return path;

            // STEP 3: split the directories, this gets rid of consecutative "/"'s
            string[] dirs = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
            // STEP 4: Get rid of directories containing . and ..
            int target = 0;

            bool isUnc = Environment.IsRunningOnWindows &&
                         root.Length > 2 && IsDsc(root[0]) && IsDsc(root[1]);

            // Set an overwrite limit for UNC paths since '\' + server + share
            // must not be eliminated by the '..' elimination algorithm.
            int limit = isUnc ? 3 : 0;

            for (int i = 0; i < dirs.Length; i++)
            {
                // WIN32 path components must be trimmed
                if (Environment.IsRunningOnWindows)
                {
                    dirs[i] = dirs[i].TrimEnd();
                }

                if (dirs[i] == "." || (i != 0 && dirs[i].Length == 0))
                {
                    continue;
                }
                else if (dirs[i] == "..")
                {
                    // don't overwrite path segments below the limit
                    if (target > limit)
                    {
                        target--;
                    }
                }
                else
                {
                    dirs[target++] = dirs[i];
                }
            }

            // STEP 5: Combine everything.
            if (target == 0 || (target == 1 && dirs[0] == ""))
            {
                return(root);
            }
            else
            {
                string ret = String.Join(DirectorySeparatorStr, dirs, 0, target);
                if (Environment.IsRunningOnWindows)
                {
                    // append leading '\' of the UNC path that was lost in STEP 3.
                    if (isUnc)
                    {
                        ret = Path.DirectorySeparatorStr + ret;
                    }

                    if (!SameRoot(root, ret))
                    {
                        ret = root + ret;
                    }

                    if (isUnc)
                    {
                        return(ret);
                    }
                    else if (!IsDsc(path[0]) && SameRoot(root, path))
                    {
                        if (ret.Length <= 2 && !ret.EndsWith(DirectorySeparatorStr))                          // '\' after "c:"
                        {
                            ret += Path.DirectorySeparatorChar;
                        }
                        return(ret);
                    }
                    else
                    {
                        string current = Directory.GetCurrentDirectory();
                        if (current.Length > 1 && current[1] == Path.VolumeSeparatorChar)
                        {
                            // DOS local file path
                            if (ret.Length == 0 || IsDsc(ret[0]))
                            {
                                ret += '\\';
                            }
                            return(current.Substring(0, 2) + ret);
                        }
                        else if (IsDsc(current[current.Length - 1]) && IsDsc(ret[0]))
                        {
                            return(current + ret.Substring(1));
                        }
                        else
                        {
                            return(current + ret);
                        }
                    }
                }
                else
                {
                    if (root != "" && ret.Length > 0 && ret [0] != '/')
                    {
                        ret = root + ret;
                    }
                }
                return(ret);
            }
        }
        public void MoveTo(String destDirName)
        {
            if (destDirName == null)
            {
                throw new ArgumentNullException("destDirName");
            }
            if (destDirName.Length == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName");
            }
            Contract.EndContractBlock();

#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
            FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, Directory.GetDemandDir(FullPath, true));
            sourceState.EnsureState();
#elif !FEATURE_CORECLR
            new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandDir, false, false).Demand();
#endif
            String fullDestDirName = Path.GetFullPathInternal(destDirName);
            String demandPath;
            if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar))
            {
                fullDestDirName = fullDestDirName + Path.DirectorySeparatorChar;
            }

            demandPath = fullDestDirName + '.';

            // Demand read & write permission to destination.  The reason is
            // we hand back a DirectoryInfo to the destination that would allow
            // you to read a directory listing from that directory.  Sure, you
            // had the ability to read the file contents in the old location,
            // but you technically also need read permissions to the new
            // location as well, and write is not a true superset of read.
#if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY
            FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, demandPath);
            destState.EnsureState();
#elif !FEATURE_CORECLR
            new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandPath).Demand();
#endif

            String fullSourcePath;
            if (FullPath.EndsWith(Path.DirectorySeparatorChar))
            {
                fullSourcePath = FullPath;
            }
            else
            {
                fullSourcePath = FullPath + Path.DirectorySeparatorChar;
            }

            if (String.Compare(fullSourcePath, fullDestDirName, StringComparison.OrdinalIgnoreCase) == 0)
            {
                throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent"));
            }

            String sourceRoot      = Path.GetPathRoot(fullSourcePath);
            String destinationRoot = Path.GetPathRoot(fullDestDirName);

            if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0)
            {
                throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot"));
            }

            if (!Win32Native.MoveFile(FullPath, destDirName))
            {
                int hr = Marshal.GetLastWin32Error();
                if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code
                {
                    hr = Win32Native.ERROR_PATH_NOT_FOUND;
                    __Error.WinIOError(hr, DisplayPath);
                }

                if (hr == Win32Native.ERROR_ACCESS_DENIED) // We did this for Win9x. We can't change it for backcomp.
                {
                    throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", DisplayPath));
                }

                __Error.WinIOError(hr, String.Empty);
            }
            FullPath     = fullDestDirName;
            OriginalPath = destDirName;
            DisplayPath  = GetDisplayName(OriginalPath, FullPath);
            demandDir    = new String[] { Directory.GetDemandDir(FullPath, true) };

            // Flush any cached information about the directory.
            _dataInitialised = -1;
        }
Beispiel #11
0
        public static void CreateDirectory(string fullPath)
        {
            // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.

            int length = fullPath.Length;

            // We need to trim the trailing slash or the code will try to create 2 directories of the same name.
            if (length >= 2 && Path.EndsInDirectorySeparator(fullPath))
            {
                length--;
            }

            // For paths that are only // or ///
            if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
            {
                throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
            }

            // We can save a bunch of work if the directory we want to create already exists.
            if (DirectoryExists(fullPath))
            {
                return;
            }

            // Attempt to figure out which directories don't exist, and only create the ones we need.
            bool           somepathexists = false;
            Stack <string> stackDir       = new Stack <string>();
            int            lengthRoot     = PathInternal.GetRootLength(fullPath);

            if (length > lengthRoot)
            {
                int i = length - 1;
                while (i >= lengthRoot && !somepathexists)
                {
                    string dir = fullPath.Substring(0, i + 1);
                    if (!DirectoryExists(dir)) // Create only the ones missing
                    {
                        stackDir.Push(dir);
                    }
                    else
                    {
                        somepathexists = true;
                    }

                    while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
                    {
                        i--;
                    }
                    i--;
                }
            }

            int count = stackDir.Count;

            if (count == 0 && !somepathexists)
            {
                string?root = Path.GetPathRoot(fullPath);
                if (!DirectoryExists(root))
                {
                    throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
                }
                return;
            }

            // Create all the directories
            int result = 0;

            Interop.ErrorInfo firstError  = default(Interop.ErrorInfo);
            string            errorString = fullPath;

            while (stackDir.Count > 0)
            {
                string name = stackDir.Pop();

                // The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).
                // We do the same.
                result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask);
                if (result < 0 && firstError.Error == 0)
                {
                    Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();

                    // While we tried to avoid creating directories that don't
                    // exist above, there are a few cases that can fail, e.g.
                    // a race condition where another process or thread creates
                    // the directory first, or there's a file at the location.
                    if (errorInfo.Error != Interop.Error.EEXIST)
                    {
                        firstError = errorInfo;
                    }
                    else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
                    {
                        // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
                        firstError  = errorInfo;
                        errorString = name;
                    }
                }
            }

            // Only throw an exception if creating the exact directory we wanted failed to work correctly.
            if (result < 0 && firstError.Error != 0)
            {
                throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
            }
        }
        public void MoveTo(String destDirName)
        {
            if (destDirName == null)
            {
                throw new ArgumentNullException("destDirName");
            }
            if (destDirName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName");
            }
            Contract.EndContractBlock();

            String fullDestDirName = Path.GetFullPath(destDirName);

            if (fullDestDirName[fullDestDirName.Length - 1] != Path.DirectorySeparatorChar)
            {
                fullDestDirName = fullDestDirName + PathHelpers.DirectorySeparatorCharAsString;
            }

            String fullSourcePath;

            if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar)
            {
                fullSourcePath = FullPath;
            }
            else
            {
                fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString;
            }

            if (PathInternal.IsDirectoryTooLong(fullSourcePath))
            {
                throw new PathTooLongException(SR.IO_PathTooLong);
            }

            if (PathInternal.IsDirectoryTooLong(fullDestDirName))
            {
                throw new PathTooLongException(SR.IO_PathTooLong);
            }

            StringComparison pathComparison = PathInternal.StringComparison;

            if (String.Equals(fullSourcePath, fullDestDirName, pathComparison))
            {
                throw new IOException(SR.IO_SourceDestMustBeDifferent);
            }

            String sourceRoot      = Path.GetPathRoot(fullSourcePath);
            String destinationRoot = Path.GetPathRoot(fullDestDirName);

            if (!String.Equals(sourceRoot, destinationRoot, pathComparison))
            {
                throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
            }

            FileSystem.Current.MoveDirectory(FullPath, fullDestDirName);

            FullPath     = fullDestDirName;
            OriginalPath = destDirName;
            DisplayPath  = GetDisplayName(OriginalPath);

            // Flush any cached information about the directory.
            Invalidate();
        }
        public void MoveTo(string destDirName)
        {
            string fullPath;

            if (destDirName == null)
            {
                throw new ArgumentNullException("destDirName");
            }
            if (destDirName.Length == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName");
            }
            new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, this.demandDir, false, false).Demand();
            string fullPathInternal = Path.GetFullPathInternal(destDirName);

            if (!fullPathInternal.EndsWith(Path.DirectorySeparatorChar))
            {
                fullPathInternal = fullPathInternal + Path.DirectorySeparatorChar;
            }
            string path = fullPathInternal + '.';

            new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, path).Demand();
            if (base.FullPath.EndsWith(Path.DirectorySeparatorChar))
            {
                fullPath = base.FullPath;
            }
            else
            {
                fullPath = base.FullPath + Path.DirectorySeparatorChar;
            }
            if (string.Compare(fullPath, fullPathInternal, StringComparison.OrdinalIgnoreCase) == 0)
            {
                throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent"));
            }
            string pathRoot = Path.GetPathRoot(fullPath);
            string strB     = Path.GetPathRoot(fullPathInternal);

            if (string.Compare(pathRoot, strB, StringComparison.OrdinalIgnoreCase) != 0)
            {
                throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot"));
            }
            if (!Win32Native.MoveFile(base.FullPath, destDirName))
            {
                int errorCode = Marshal.GetLastWin32Error();
                switch (errorCode)
                {
                case 2:
                    errorCode = 3;
                    __Error.WinIOError(errorCode, base.DisplayPath);
                    break;

                case 5:
                    throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", new object[] { base.DisplayPath }));
                }
                __Error.WinIOError(errorCode, string.Empty);
            }
            base.FullPath         = fullPathInternal;
            base.OriginalPath     = destDirName;
            base.DisplayPath      = GetDisplayName(base.OriginalPath, base.FullPath);
            this.demandDir        = new string[] { Directory.GetDemandDir(base.FullPath, true) };
            base._dataInitialised = -1;
        }
Beispiel #14
0
        public void MoveTo(string destDirName)
        {
            if (destDirName == null)
            {
                throw new ArgumentNullException(nameof(destDirName));
            }
            if (destDirName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName));
            }
            Contract.EndContractBlock();

            string destination = Path.GetFullPath(destDirName);
            string destinationWithSeparator = destination;

            if (destinationWithSeparator[destinationWithSeparator.Length - 1] != Path.DirectorySeparatorChar)
            {
                destinationWithSeparator = destinationWithSeparator + PathHelpers.DirectorySeparatorCharAsString;
            }

            string fullSourcePath;

            if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar)
            {
                fullSourcePath = FullPath;
            }
            else
            {
                fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString;
            }

            if (PathInternal.IsDirectoryTooLong(fullSourcePath))
            {
                throw new PathTooLongException(SR.IO_PathTooLong);
            }

            if (PathInternal.IsDirectoryTooLong(destinationWithSeparator))
            {
                throw new PathTooLongException(SR.IO_PathTooLong);
            }

            StringComparison pathComparison = PathInternal.StringComparison;

            if (string.Equals(fullSourcePath, destinationWithSeparator, pathComparison))
            {
                throw new IOException(SR.IO_SourceDestMustBeDifferent);
            }

            string sourceRoot      = Path.GetPathRoot(fullSourcePath);
            string destinationRoot = Path.GetPathRoot(destinationWithSeparator);

            if (!string.Equals(sourceRoot, destinationRoot, pathComparison))
            {
                throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
            }

            // Windows will throw if the source file/directory doesn't exist, we preemptively check
            // to make sure our cross platform behavior matches NetFX behavior.
            if (!Exists && !FileSystem.Current.FileExists(FullPath))
            {
                throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath));
            }

            if (FileSystem.Current.DirectoryExists(destinationWithSeparator))
            {
                throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator));
            }

            FileSystem.Current.MoveDirectory(FullPath, destination);

            FullPath     = destinationWithSeparator;
            OriginalPath = destDirName;
            DisplayPath  = GetDisplayName(OriginalPath);

            // Flush any cached information about the directory.
            Invalidate();
        }