Example #1
0
        public async Task TaskUploadNewFile(IFileSystemItem file)
        {
            var safeFilePath = Regex.Replace(file.FullPath.Replace(RootPath, ""), "[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]", "_");
            var savedPath    = await _fileManager.SaveFileAsync(DataFeedId, RunId, safeFilePath, _dataFeedFileLoader.GetFileContent(file.FullPath));

            _savedFiles.Add(savedPath);
        }
Example #2
0
        /// <summary>
        /// Deletes the selected item or folder from the ListBox.
        /// </summary>
        /// <returns>A Boolean value that indicates whether the file or folder was successfully deleted.</returns>
        internal async Task <bool?> DeleteFileOrFolderAsync(FileSystemItemViewModel _selectedFileObject)
        {
            bool?isSuccess = false;

            try
            {
                // Gets the FileSystemItem that is selected in the bound ListBox control.
                IFileSystemItem fileOrFolderToDelete = _selectedFileObject.FileSystemItem;

                // This results in a call to the service.
                await fileOrFolderToDelete.DeleteAsync();

                isSuccess = true;
            }
            catch (Microsoft.Data.OData.ODataErrorException)
            {
                isSuccess = null;
            }
            catch (NullReferenceException)
            {
                isSuccess = null;
            }

            return(isSuccess);
        }
Example #3
0
        /// <summary>
        /// Update the currently selected item by appending new text.
        /// </summary>
        /// <param name="_selectedFileObject">The file selected in the ListBox.</param>
        /// <param name="fileText">The updated text contents of the file.</param>
        /// <returns>A Boolean value that indicates whether the text file was successfully updated.</returns>
        internal async Task <bool> UpdateTextFileAsync(FileSystemItemViewModel _selectedFileObject, string fileText)
        {
            File file;

            byte[] byteArray;
            bool   isSuccess = false;

            try
            {
                // Get a handle on the selected item.
                IFileSystemItem myFile = _selectedFileObject.FileSystemItem;
                file = myFile as File;
                string updateTime = "\n\r\n\rLast update at " + DateTime.Now.ToLocalTime().ToString();
                byteArray = Encoding.UTF8.GetBytes(fileText + updateTime);

                using (MemoryStream stream = new MemoryStream(byteArray))
                {
                    // Update the file. This results in a call to the service.
                    await file.UploadAsync(stream);

                    isSuccess = true; // We've updated the file.
                }
            }
            catch (ArgumentException)
            {
                isSuccess = false;
            }

            return(isSuccess);
        }
Example #4
0
 void CreateStructure(IFileSystemItem[] fileSystemItems)
 {
     foreach (var fs in fileSystemItems.OfType<IDirectory>())
         fs.MustExist();
     foreach (var fs in fileSystemItems.OfType<IFile>())
         fs.MustExist();
 }
Example #5
0
 private Node GetNodeFromFSItem(IFileSystemItem item)
 {
     if (item is IPhysicalFile)
     {
         return(null);
     }
     if (item is IStringFile)
     {
         return(null);
     }
     if (item is IFile file)
     {
         return(file.Content as Node);
     }
     if (item is IDirectory directory)
     {
         foreach (var dirFile in directory.Items)
         {
             var res = GetNodeFromFSItem(dirFile);
             if (res != null)
             {
                 return(res);
             }
         }
         return(null);
     }
     return(null);
 }
        public async Task DeleteFile(string id)
        {
            var             client         = new SharePointClient(ServiceEndpointUri, GetAccessToken);
            IFileSystemItem fileSystemItem = await client.Files.GetByIdAsync(id);

            await fileSystemItem.DeleteAsync();
        }
        public void CopyTo(IFileSystemItem where)
        {
            VerifyExists();
            var currentLock = _lock;

            if (currentLock != null && currentLock.Value != FileShare.Read && currentLock.Value != FileShare.ReadWrite)
            {
                throw new IOException("Cannot copy file as someone opened it without shared read access");
            }
            if (where is InMemoryFile)
            {
                if (where.Exists)
                {
                    throw new IOException("File already exists");
                }
                ((InMemoryFile) where).CopyFromFile(this);
            }
            else if (where is InMemoryDirectory)
            {
                ((InMemoryFile)((InMemoryDirectory) where).GetFile(Name)).CopyFromFile(this);
            }
            else
            {
                throw new InvalidOperationException("The target type doesn't match the file system of the current file.");
            }
        }
        /// <summary>
        /// Removes empty child directory
        /// </summary>
        /// <param name="name">Directory name</param>
        /// <exception cref="InvalidOperationException">
        /// Throws if child item is not a directory, or if child directory is not empty,
        /// or if the item kind is not volume or directory, or if a child item with the specified name is not exists
        /// </exception>
        public void RemoveChildDirectory(string name)
        {
            this.ValidateCanHasChildItems();

            IFileSystemItem directory = FileSystemItemFactory.CreateDirectory(name); // validate name

            IFileSystemItem child = this.ChildItems.Where(item => FileSystemItemNameComparer.Equals(directory.Name, item.Name)).FirstOrDefault();

            if (child is null)
            {
                throw new InvalidOperationException("Directory with the specified name is not exists.");
            }

            if (child.Kind != FileSystemItemKind.Directory)
            {
                throw new InvalidOperationException("Item with the specified name is not a directory.");
            }

            if (child.ChildItems.Count > 0)
            {
                throw new InvalidOperationException("Directory with the specified name is not empty.");
            }

            this.childItems.Remove(child);
        }
Example #9
0
        public string UnlockFile(string userName, string currentDirectory, string fileName)
        {
            currentDirectory = NormalizeCurrentDirectory(currentDirectory);
            if (!PathUtils.IsAbsolutePath(fileName))
            {
                fileName = PathUtils.CombinePath(currentDirectory, fileName);
            }

            string[] directoryParts = PathUtils.SplitPath(fileName);

            IFileSystemItem currentItem = this.root;

            for (int i = 0; i < directoryParts.Length; i++)
            {
                currentItem = currentItem.ChildItems.FirstOrDefault(item => FileSystemItemNameComparer.Equals(item.Name, directoryParts[i]));
                if (currentItem is null)
                {
                    throw new FileSystemConsoleException("Destination path is not exists.");
                }
            }

            if (currentItem.Kind != FileSystemItemKind.File)
            {
                throw new FileSystemConsoleException("Destination path is not a file.");
            }

            currentItem.Unlock(userName);

            return(fileName);
        }
        /// <summary>
        /// Removes child item
        /// </summary>
        /// <param name="child">Child item</param>
        /// <exception cref="ArgumentNullException">Throws if the child item is null</exception>
        /// <exception cref="InvalidOperationException">
        /// Throws if the item is not a volume or a directory,
        /// or if the child item is not a directory or a file,
        /// or if the child item is a locked file,
        /// or if the item do not contain the specified child
        /// </exception>
        public void RemoveChild(IFileSystemItem child)
        {
            this.ValidateCanHasChildItems();

            if (child is null)
            {
                throw new ArgumentNullException(nameof(child));
            }

            if (child.Kind != FileSystemItemKind.Directory && child.Kind != FileSystemItemKind.File)
            {
                throw new InvalidOperationException("Child item is not a directory or a file.");
            }

            if (!this.ChildItems.Contains(child))
            {
                throw new InvalidOperationException("Item do not have the specified child item.");
            }

            if (child.IsLocked)
            {
                throw new InvalidOperationException("Child item is locked.");
            }

            this.childItems.Remove(child);
        }
        /// <summary>
        /// Removes child file
        /// </summary>
        /// <param name="name">File name</param>
        /// <exception cref="InvalidOperationException">
        /// Throws if child item is not a file, or if the item kind is not volume or directory,
        /// or if a child item with the specified name is not exists,
        /// or if a child item with the specified name is locked
        /// </exception>
        public void RemoveChildFile(string name)
        {
            this.ValidateCanHasChildItems();

            IFileSystemItem file = FileSystemItemFactory.CreateFile(name); // validate name

            IFileSystemItem child = this.ChildItems.Where(item => FileSystemItemNameComparer.Equals(file.Name, item.Name)).FirstOrDefault();

            if (child is null)
            {
                throw new InvalidOperationException("File with the specified name is not exists.");
            }

            if (child.Kind != FileSystemItemKind.File)
            {
                throw new InvalidOperationException("Item with the specified name is not a file.");
            }

            if (child.IsLocked)
            {
                throw new InvalidOperationException("File with the specified name is locked.");
            }

            this.childItems.Remove(child);
        }
Example #12
0
        public string DeleteTree(string currentDirectory, string directory)
        {
            currentDirectory = NormalizeCurrentDirectory(currentDirectory);
            if (!PathUtils.IsAbsolutePath(directory))
            {
                directory = PathUtils.CombinePath(currentDirectory, directory);
            }

            string[] directoryParts = PathUtils.SplitPath(directory);

            IFileSystemItem currentItem = this.root;

            for (int i = 0; i < directoryParts.Length; i++)
            {
                currentItem = currentItem.ChildItems.FirstOrDefault(item => FileSystemItemNameComparer.Equals(item.Name, directoryParts[i]));
                if (currentItem is null)
                {
                    throw new FileSystemConsoleException("Destination path is not exists.");
                }
            }

            if (currentItem.Kind != FileSystemItemKind.Directory)
            {
                throw new FileSystemConsoleException("Destination path is not a directory.");
            }

            if (currentItem.HasLocks())
            {
                throw new FileSystemConsoleException("Directory or its subdirectories contain one or more locked files.");
            }

            currentItem.Parent.RemoveChildDirectoryWithTree(currentItem.Name);

            return(directory);
        }
Example #13
0
        public bool Rename(IFileSystemItem item, string newName, bool overwrite = false)
        {
            FtpExists exists      = overwrite ? FtpExists.Overwrite : FtpExists.Skip;
            string    currentPath = item.GetUri().AbsolutePath;

            try
            {
                if (item.IsDirectory())
                {
                    string upperPath = IO.Path.GetFullPath(IO.Path.Combine(currentPath, ".."));
                    string destUri   = IO.Path.GetFullPath(IO.Path.Combine(upperPath, newName));
                    return(client.MoveDirectory(currentPath, destUri, exists));
                }
                else
                {
                    string destUri = IO.Path.GetFullPath(IO.Path.Combine(currentPath, newName));
                    return(client.MoveFile(item.GetUri().AbsoluteUri, destUri, exists));
                }
            }
            catch (Exception e)
            {
                ExceptionHandler.LogException(e);
            }
            return(false);
        }
Example #14
0
 public bool AddItem(IFileSystemItem item, Directory directory, bool overwrite)
 {
     try
     {
         FtpExists exists = overwrite ? FtpExists.Overwrite : FtpExists.Skip;
         if (item.IsDirectory())
         {
             client.CreateDirectory(IO.Path.Combine(directory.GetUri().AbsolutePath, item.Name));
             List <IO.FileInfo> fileInfos = new List <IO.FileInfo>();
             foreach (IFileSystemItem subitem in (item as Directory).EnumerateChildren())
             {
                 fileInfos.Add(subitem.FileInfo);
             }
             int uploaded = client.UploadFiles(
                 fileInfos,
                 directory.GetUri().AbsolutePath,
                 exists,
                 createRemoteDir: true);
             return(uploaded == fileInfos.Count);
         }
         else
         {
             return(AddFile(item as File, directory, overwrite));
         }
     }
     catch (Exception e)
     {
         ExceptionHandler.LogException(e);
     }
     return(false);
 }
        public void MoveTo(IFileSystemItem item)
        {
            if (!item.Path.IsRooted)
            {
                throw new ArgumentException("Has to be a fully-qualified path for a move to succeed.");
            }
            var newDirectory = (InMemoryDirectory)FileSystem.GetDirectory(item.Path.FullPath);

            newDirectory.Exists = true;
            lock (ChildFiles)
                lock (ChildDirectories)
                    lock (newDirectory.ChildFiles)
                        lock (newDirectory.ChildDirectories)
                        {
                            newDirectory.ChildFiles       = ChildFiles;
                            newDirectory.ChildDirectories = ChildDirectories;

                            foreach (var file in newDirectory.ChildFiles.OfType <InMemoryFile>())
                            {
                                file.Parent = newDirectory;
                            }

                            foreach (var file in newDirectory.ChildDirectories.OfType <InMemoryDirectory>())
                            {
                                file.Parent = newDirectory;
                            }

                            Exists           = false;
                            ChildFiles       = new List <InMemoryFile>();
                            ChildDirectories = new List <InMemoryDirectory>();
                        }
        }
Example #16
0
 /// <summary>
 /// Moves item to current directory under destination name
 /// </summary>
 /// <param name="itemToMove"> Moved file system item </param>
 /// <param name="destinationPath"> Destination directory name </param>
 private void Move(IFileSystemItem itemToMove, string destinationPath)
 {
     try
     {
         if (itemToMove.IsDirectory)
         {
             Directory.Move(itemToMove.Path, Path.Combine(destinationPath, itemToMove.Name));
         }
         else
         {
             File.Move(itemToMove.Path, Path.Combine(destinationPath, itemToMove.Name));
         }
     }
     catch (UnauthorizedAccessException unauthorizedAccessException)
     {
         _logger.Info($"Unauthorized access to {CurrentDirectory}", unauthorizedAccessException);
     }
     catch (DirectoryNotFoundException exception)
     {
         _logger.Error($"Given soruce path: {itemToMove.Path}, is invalid",
                       exception);
         throw new InvalidPathException(itemToMove.Path, innerException: exception);
     }
     catch (Exception exception)
     {
         _logger.Error("One of the given paths may be invalid, or file system item is used by another process", exception);
         throw new MoveOperationException(itemToMove.Path, destinationPath, innerException: exception);
     }
 }
Example #17
0
        public string ChangeDirectory(string currentDirectory, string directory)
        {
            currentDirectory = NormalizeCurrentDirectory(currentDirectory);
            if (!PathUtils.IsAbsolutePath(directory))
            {
                directory = PathUtils.CombinePath(currentDirectory, directory);
            }

            string[] directoryParts = PathUtils.SplitPath(directory);

            IFileSystemItem currentItem = this.root;

            for (int i = 0; i < directoryParts.Length; i++)
            {
                currentItem = currentItem.ChildItems.FirstOrDefault(item => FileSystemItemNameComparer.Equals(item.Name, directoryParts[i]));
                if (currentItem is null)
                {
                    throw new FileSystemConsoleException("Destination path is not exists.");
                }
            }

            if (currentItem.Kind != FileSystemItemKind.Volume && currentItem.Kind != FileSystemItemKind.Directory)
            {
                throw new FileSystemConsoleException("Destination path is not a volume or a directory.");
            }

            return(directory);
        }
Example #18
0
        private static void CopyItemTree(IFileSystemItem item, IFileSystemItem destItem)
        {
            if (item.Kind != FileSystemItemKind.Directory && item.Kind != FileSystemItemKind.File)
            {
                throw new ArgumentException(Invariant($"{nameof(item)} is not a directory or a file."), nameof(item));
            }

            if (destItem.Kind != FileSystemItemKind.Volume && destItem.Kind != FileSystemItemKind.Directory)
            {
                throw new ArgumentException(Invariant($"{nameof(destItem)} is not a volume or directory."), nameof(item));
            }

            IFileSystemItem CopyItem()
            {
                switch (item.Kind)
                {
                case FileSystemItemKind.Directory:
                    return(destItem.AddChildDirectory(item.Name));

                case FileSystemItemKind.File:
                    return(destItem.AddChildFile(item.Name));

                default:
                    throw new ArgumentException(Invariant($"{nameof(item)} is not a directory or a file."), nameof(item));
                }
            }

            IFileSystemItem itemCopy = CopyItem();

            item.ChildItems.ForEach(child => CopyItemTree(child, itemCopy));
        }
    string WriteIdNameAndLongName(IFileSystemItem path)
    {
        string id = GetIdFromPath(path);

        WriteAttribute("Id", id);
        WriteNameAndLongName(path);
        return(id);
    }
        public async Task DeleteFile(string id)
        {
            var client = await EnsureClientCreated();

            IFileSystemItem fileSystemItem = await client.Files.GetByIdAsync(id);

            await fileSystemItem.DeleteAsync();
        }
Example #21
0
        public void MoveTo(IFileSystemItem newFileName)
        {
            var oldPath = Path.FullPath;

            DirectoryInfo.Refresh();
            DirectoryInfo.MoveTo(newFileName.Path.FullPath);
            DirectoryInfo = new DirectoryInfo(oldPath);
        }
Example #22
0
 /// <summary>
 /// Создает экземпляр класса
 /// </summary>
 /// <param name="service">Интерфейс службы управления подключенного терминала</param>
 /// <param name="current">Элемент файловой системы терминала,
 /// с которого нужно начинать загрузку</param>
 /// <param name="storageFolder">Папка для сохранения скачанных данных</param>
 public FormDownloadWorker(IManagementService service, IFileSystemItem current,
     String storageFolder)
 {
     InitializeComponent();
     _service = service;
     _current = current;
     _storageFolder = storageFolder;
     _filesProcessed = 0;
 }
Example #23
0
 public static FileObject ToObject(this IFileSystemItem item)
 {
     return(new FileObject()
     {
         Provider = item.Provider,
         Path = item.Path,
         ItemType = item.ItemType,
     });
 }
Example #24
0
 public virtual void CopyFrom(IFileSystemItem @from)
 {
     Id           = @from.Id;
     ParentId     = @from.ParentId;
     ItemType     = @from.ItemType;
     Path         = @from.Path;
     Name         = @from.Name;
     CreateDate   = @from.CreateDate;
     ModifiedDate = @from.ModifiedDate;
 }
        public static IFileSystemItem CreateRoot(string name)
        {
            IFileSystemItem root = CreateItemInternal(FileSystemItemKind.Root, name);

            IFileSystemItem defaultVolume = CreateVolume(PathUtils.Consts.ValidVolumeNames[0]);

            root.AddChild(defaultVolume);

            return(root);
        }
Example #26
0
 public virtual void CopyTo(IFileSystemItem @to)
 {
     @to.Id           = Id;
     @to.ParentId     = ParentId;
     @to.ItemType     = ItemType;
     @to.Path         = Path;
     @to.Name         = Name;
     @to.CreateDate   = CreateDate;
     @to.ModifiedDate = ModifiedDate;
 }
Example #27
0
        private static void PrintTreeHelper(IFileSystemItem item, StringBuilder builder, bool printRoot)
        {
            PrintItem(item, builder, printRoot);

            item.ChildItems.GroupBy(child => child.Kind).OrderBy(group => group.Key).ForEach(
                childGroup => childGroup.OrderBy(child => child.Name, FileSystemItemNameComparer).ForEach(
                    child => PrintTreeHelper(child, builder, printRoot)
                    )
                );
        }
Example #28
0
        public virtual async Task <ITag> CreateTag(IFileSystemItem item, string name, string value)
        {
            var tag = new Tag(item, name, value);

            await Tags.AddAsync(tag);

            await SaveChangesAsync(true);

            return(tag);
        }
    private void WriteShortcut(Shortcut shortcut)
    {
        IFileSystemItem shortcutTarget = ResolveFile(shortcut.Path);

        if (shortcutTarget == null)
        {
            throw new ArgumentException(string.Format("Could not find file '{0}' required by shortcut '{1}'", shortcut.Path, shortcut.Name));
        }
        WriteShortcut(shortcut.Name, shortcutTarget, GetIdFromPath(shortcutTarget.Parent));
    }
    void WriteFile(IFileSystemItem file)
    {
        StartElement("File");
        WriteIdNameAndLongName(file);
        WriteAttribute("Source", file.FullPath);
        WriteAttribute("DiskId", "1");
        WriteAttribute("Vital", "yes");

        EndElement();
    }
Example #31
0
        public async Task <bool> RenameFile(string id, string filename)
        {
            var client = await EnsureClientCreated();

            IFileSystemItem fileSystemItem = await client.Files.GetByIdAsync(id);

            fileSystemItem.Name = filename;
            await fileSystemItem.UpdateAsync();

            return(true);
        }
        public FileSystemItemViewModel(IFileSystemItem fileSystemItem)
        {
            if (fileSystemItem == null)
            {
                throw new System.ArgumentNullException("fileSystemItem");
            }

            _fileSystemItem = fileSystemItem;

            _name = fileSystemItem.Name;
        }
        public FileSystemItemViewModel(IFileSystemItem fileSystemItem)
        {
            if (fileSystemItem == null)
            {
                throw new System.ArgumentNullException("fileSystemItem");
            }

            _fileSystemItem = fileSystemItem;

            _name = fileSystemItem.Name;
        }
Example #34
0
		public string RelativePathFor(IFileSystemItem file)
		{
			Stack<string> path = new Stack<string>();
			IFileSystemItem current = file;
			do
			{
				path.Push(current.Name);
				current = current.Parent;
			}
			while (current != _root);
			return path.Skip(1).Aggregate(path.Peek(), (acc, item) => acc + @"\" + item);
		}
Example #35
0
		public void CopyTo(IFileSystemItem where)
		{
			VerifyExists();
			var currentLock = _lock;
			if (currentLock != null && currentLock.Value != FileShare.Read && currentLock.Value != FileShare.ReadWrite)
				throw new IOException("Cannot copy file as someone opened it without shared read access");
			if (where is InMemoryFile)
			{
				if (where.Exists)
					throw new IOException("File already exists");
				((InMemoryFile) where).CopyFromFile(this);
			}
			else if (where is InMemoryDirectory)
				((InMemoryFile) ((InMemoryDirectory) where).GetFile(Name)).CopyFromFile(this);
			else
				throw new InvalidOperationException("The target type doesn't match the file system of the current file.");
		}
Example #36
0
        private void BuildTree(String aText, List<String> summary, IFileSystemItem root,
            TreeView aView, Boolean insertSubfolders)
        {
            summary.Add(String.Format("Имя папки: {0}", root.Name));
            summary.Add(new String('-', 50));
            summary.Add(String.Empty);

            aView.BeginUpdate();
            try
            {
                aView.Nodes.Clear();
                TreeNode aRoot = InsertFsi(summary, root, insertSubfolders, true);
                aRoot.Text = aText;
                aView.Nodes.Add(aRoot);
                aRoot.Expand();
                aView.SelectedNode = aRoot;
            }
            finally
            {
                aView.EndUpdate();
            }
        }
Example #37
0
        private TreeNode InsertFsi(List<String> summary, IFileSystemItem fsi,
            Boolean insertSubfolders, Boolean isRoot)
        {
            // рисунок нода
            Int32 imageIndex;
            if (isRoot)
                imageIndex = 0;
            else
                imageIndex = fsi.ItemType == FileSystemItemType.Directory ? 1 : 2;

            // создаем нод
            TreeNode aNode = new TreeNode(fsi.ToString());
            aNode.ImageIndex = imageIndex;
            aNode.SelectedImageIndex = imageIndex;

            // данные нода
            aNode.Tag = fsi;

            // в отчет
            if (fsi.ItemType == FileSystemItemType.File)
                summary.Add(String.Format("{0}, {1}", fsi.Name, fsi.Version));

            // добавляем вложенные элементы
            foreach (IFileSystemItem subFsi in fsi.SubItems)
            {
                if (subFsi.ItemType == FileSystemItemType.File)
                    aNode.Nodes.Add(InsertFsi(summary, subFsi, false, false));
                else
                {
                    if (insertSubfolders)
                        aNode.Nodes.Add(InsertFsi(summary, subFsi, insertSubfolders, false));
                }
            }

            // возвращаем нод
            return aNode;
        }
		private void AssertPathAndName(string expectedPath, IFileSystemItem fsi)
		{
			Assert.AreEqual(expectedPath, fsi.FullPath);
			Assert.AreEqual(Path.GetFileName(expectedPath), fsi.Name);
		}
Example #39
0
		internal static void AssertFile(IFileSystemItem expected, WixElement actual)
		{
			Assert.AreEqual(expected.FullPath, actual.GetAttribute("Source"));
		}
Example #40
0
 public void MoveTo(IFileSystemItem item)
 {
 }
Example #41
0
	string WriteIdNameAndLongName(IFileSystemItem path)
	{
		string id = GetIdFromPath(path);
		WriteAttribute("Id", id);
		WriteNameAndLongName(path);
		return id;
	}
		public abstract void MoveTo(IFileSystemItem item);
Example #43
0
 /// <summary>
 /// Добавляет элемент файловой системы в сводный отчет о версиях
 /// </summary>
 /// <param name="sw">Поток отчета</param>
 /// <param name="fsi">Элемент файловой системы</param>
 /// <param name="insertSubFolders">Добавлять вложенные папки</param>
 private void InsertFsiToTree(StreamWriter sw, IFileSystemItem fsi, 
     Boolean insertSubFolders)
 {
     sw.WriteLine(String.Format("{0}, {1}", fsi.Name, fsi.Version));
     foreach (IFileSystemItem subFsi in fsi.SubItems)
     {
         if (subFsi.ItemType == FileSystemItemType.File)
             InsertFsiToTree(sw, subFsi, false);
         else
         {
             if (insertSubFolders)
                 InsertFsiToTree(sw, subFsi, insertSubFolders);
         }
     }
 }
Example #44
0
	void WriteNameAndLongName(IFileSystemItem path)
	{
		WriteAttribute("Name", path.Name);
	}
Example #45
0
		public void MoveTo(IFileSystemItem newFileName)
		{
			var currentLock = _lock;
			if (currentLock != null) throw new IOException("File is locked, please try again later.");
			CopyTo(newFileName);
			Delete();
		}
Example #46
0
		public void MoveTo(IFileSystemItem item)
		{
			UnderlyingDirectory.MoveTo(item);
		}
Example #47
0
		public void CopyTo(IFileSystemItem item)
		{
			UnderlyingDirectory.CopyTo(item);
		}
Example #48
0
	string GetIdFromPath(IFileSystemItem fileSystemItem)
	{
		var path = fileSystemItem.FullPath;
		string existing;
		if (_fileIdMapping.TryGetValue(path, out existing))
			return existing;

		string newId = "_" + NewGuid().Replace('-', '_');
		_fileIdMapping.Add(path, newId);
		return newId;
	}
Example #49
0
		internal static void AssertWixDirectory(IFileSystemItem expected, XmlElement actual)
		{
			Assert.AreEqual("Directory", actual.Name);
			Assert.AreEqual(expected.Name, actual.GetAttribute("Name"));
		}
		public void MoveTo(IFileSystemItem item)
		{
			Contract.Requires(item != null);
			throw new System.NotImplementedException();
		}
Example #51
0
    void WriteShortcut(string displayName, IFileSystemItem fileSystemItem, string workingDirectory)
	{
		string fileId = GetIdFromPath(fileSystemItem);

		StartElement("Shortcut");
		WriteAttribute("Id", "s_" + fileId);

		string ext = Path.GetExtension(fileSystemItem.Name).Substring(1).ToLower();
		WriteAttribute("Icon", ext + ".ico");
		WriteAttribute("IconIndex", "0");
		WriteAttribute("Directory", "TargetMenuFolder");
		WriteAttribute("Name", displayName);
		WriteAttribute("Description", displayName);
		WriteAttribute("Show", "normal");
		WriteAttribute("WorkingDirectory", workingDirectory);
		WriteAttribute("Target", "[#" + fileId + "]");
		EndElement();
	}
 public void CopyTo(IFileSystemItem item)
 {
     wrapped.CopyTo(item);
 }
 public void MoveTo(IFileSystemItem item)
 {
     wrapped.MoveTo(item);
 }
Example #54
0
 public void CopyTo(IFileSystemItem item)
 {
 }
		public abstract void CopyTo(IFileSystemItem item);
Example #56
0
 public void MoveTo(IFileSystemItem item)
 {
     throw new NotImplementedException();
 }
Example #57
0
 /// <summary>
 /// Добавляет дерево файлов в отчет о версиях
 /// </summary>
 /// <param name="sw">Поток для записи данных</param>
 /// <param name="root">Корневой элемент файловой системы</param>
 /// <param name="insertSubFolders">Добавлять или нет подпапки</param>
 private void AddTreeToFile(StreamWriter sw, IFileSystemItem root,
     Boolean insertSubFolders)
 {
     sw.WriteLine(String.Format("Имя папки: {0}", root.Name));
     sw.WriteLine(new String('-', 50));
     sw.WriteLine(String.Empty);
     InsertFsiToTree(sw, root, insertSubFolders);
 }
 public static bool PathEquals(this IFileSystemItem item, IFileSystemItem compareTo)
 {
     return string.Equals(item.AbsolutePath(), compareTo.AbsolutePath(), StringComparison.OrdinalIgnoreCase);
 }
Example #59
0
	void WriteFile(IFileSystemItem file)
	{
		StartElement("File");
		WriteIdNameAndLongName(file);
		WriteAttribute("Source", file.FullPath);
		WriteAttribute("DiskId", "1");
		WriteAttribute("Vital", "yes");

		EndElement();
	}
Example #60
0
        /// <summary>
        /// Загрузка элемента файловой системы
        /// </summary>
        /// <param name="current">Текущий элемент файловой системы</param>
        /// <param name="storageFolder">Папка для записи элемента</param>
        /// <param name="e">Параметры обработчика события</param>
        private void DownloadItem(IFileSystemItem current, String storageFolder,
            DoWorkEventArgs e)
        {
            // проверяем статус завершения
            if (backgroundWorker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            // в зависимости от типа элемента
            if (current.ItemType == FileSystemItemType.File)
            {
                // файл
                // запрашиваем поток для чтения данных
                using (Stream serverStream = _service.GetFile(current.Name))
                {
                    // формируем имя локального файла
                    String fileName = storageFolder + Path.GetFileName(current.Name);
                    
                    // открываем поток для записи
                    using (FileStream clientStream = new FileStream(fileName,
                        FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        // выделяем память под временный буфер
                        Byte[] data = new Byte[_dataSize];

                        // читаем из серверного потока
                        Int32 readBytes;
                        while (serverStream.Position < serverStream.Length)
                        {
                            readBytes = serverStream.Read(data, 0, _dataSize);
                            if (readBytes > 0)
                            {
                                // записываем в клиентский поток
                                clientStream.Write(data, 0, readBytes);
                            }
                        }
                    }
                    // сообщаем о прогрессе выполнения задачи
                    backgroundWorker.ReportProgress(0, current.Name);
                }
            }
            else
            {
                // не файл
                // загружаем все подчиненные элементы
                foreach (IFileSystemItem subItem in current.SubItems)
                {
                    // формируем реальное имя хранилища
                    StringBuilder realStorage = new StringBuilder(storageFolder);
                    if (subItem.ItemType != FileSystemItemType.File)
                    {
                        realStorage.Append(Path.GetFileName(subItem.Name));
                        realStorage.Append(Path.DirectorySeparatorChar);

                        // создаем папку-хранилище
                        Directory.CreateDirectory(realStorage.ToString());
                    }

                    // вызываем метод рекурсивно
                    DownloadItem(subItem, realStorage.ToString(), e);
                }
            }
        }