Example #1
0
 public Node(string name, FileAttributes attrs)
 {
     Attributes = attrs;
     Name = name;
     Parents = new HashSet<Node>();
     Contains = new HashSet<Node>();
 }
Example #2
0
 private static string GetAttributeLetter(FileAttributes fileAttributes, FileAttributes attributeToSearch, string attributeLetter)
 {
     if ((fileAttributes & attributeToSearch) == attributeToSearch)
         return attributeLetter;
     else
         return "-";
 }
Example #3
0
        public static long Pack(FileAttributes fa)
        {
            long ret = 0;
            if ((fa & FileAttributes.Directory) > 0) ret |= Directory;

            return ret;
        }
Example #4
0
 public FileTreeNodeProperty(string _name, FileTreeNodeType _type, string _fullPath, FileAttributes _fileSystemAttributes)
 {
     name__ = _name;
     type__ = _type;
     fullPath__ = _fullPath;
     fileSystemAttributes__ = _fileSystemAttributes;
 }
        public static void AddTree(DirNode dirNode, string dirPrefix, string filePrefix, int width, int depth, int fileSizeInKB, FileAttributes? fa = null, DateTime? lmt = null)
        {
            for (int i = 0; i < width; ++i)
            {
                string fileName = i == 0 ? filePrefix : filePrefix + "_" + i;
                FileNode fileNode = new FileNode(fileName)
                {
                    SizeInByte = 1024L * fileSizeInKB,
                    FileAttr = fa,
                    LastModifiedTime = lmt,
                };

                dirNode.AddFileNode(fileNode);
            }

            if (depth > 0)
            {
                for (int i = 0; i < width; ++i)
                {
                    string dirName = i == 0 ? dirPrefix : dirPrefix + "_" + i;
                    DirNode subDirNode = dirNode.GetDirNode(dirName);
                    if (subDirNode == null)
                    {
                        subDirNode = new DirNode(dirName);
                        dirNode.AddDirNode(subDirNode);
                    }

                    DMLibDataHelper.AddTree(subDirNode, dirPrefix, filePrefix, width, depth - 1, fileSizeInKB, fa, lmt: lmt);
                }
            }
        }
        internal static IEnumerable<IFileSystemInformation> EnumerateChildrenInternal(
            string directory,
            ChildType childType,
            string searchPattern,
            System.IO.SearchOption searchOption,
            FileAttributes excludeAttributes,
            IFileService fileService)
        {
            // We want to be able to see all files as we recurse and open new find handles (that might be over MAX_PATH).
            // We've already normalized our base directory.
            string extendedDirectory = Paths.AddExtendedPrefix(directory);

            // The assertion here is that we want to find files that match the desired pattern in all subdirectories, even if the
            // subdirectories themselves don't match the pattern. That requires two passes to avoid overallocating for directories
            // with a large number of files.

            // First look for items that match the given search pattern in the current directory
            using (FindOperation findOperation = new FindOperation(Paths.Combine(extendedDirectory, searchPattern)))
            {
                FindResult findResult;
                while ((findResult = findOperation.GetNextResult()) != null)
                {
                    bool isDirectory = (findResult.Attributes & FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == FileAttributes.FILE_ATTRIBUTE_DIRECTORY;

                    if ((findResult.Attributes & excludeAttributes) == 0
                        && findResult.FileName != "."
                        && findResult.FileName != ".."
                        && ((isDirectory && childType == ChildType.Directory)
                            || (!isDirectory && childType == ChildType.File)))
                    {
                        yield return FileSystemInformation.Create(findResult, directory, fileService);
                    }
                }
            }

            if (searchOption != System.IO.SearchOption.AllDirectories) yield break;

            // Now recurse into each subdirectory
            using (FindOperation findOperation = new FindOperation(Paths.Combine(extendedDirectory, "*"), directoriesOnly: true))
            {
                FindResult findResult;
                while ((findResult = findOperation.GetNextResult()) != null)
                {
                    // Unfortunately there is no guarantee that the API will return only directories even if we ask for it
                    bool isDirectory = (findResult.Attributes & FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == FileAttributes.FILE_ATTRIBUTE_DIRECTORY;

                    if ((findResult.Attributes & excludeAttributes) == 0
                        && isDirectory
                        && findResult.FileName != "."
                        && findResult.FileName != "..")
                    {
                        foreach (var child in EnumerateChildrenInternal(Paths.Combine(directory, findResult.FileName), childType, searchPattern,
                            searchOption, excludeAttributes, fileService))
                        {
                            yield return child;
                        }
                    }
                }
            }
        }
Example #7
0
        private static string FromFileAttribs(FileAttributes attribs)
        {
            var str = new StringBuilder(9);

            if ((attribs & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                str.Append('R');
            if ((attribs & FileAttributes.Archive) == FileAttributes.Archive)
                str.Append('A');
            if ((attribs & FileAttributes.System) == FileAttributes.System)
                str.Append('S');
            if ((attribs & FileAttributes.Hidden) == FileAttributes.Hidden)
                str.Append('H');
            if ((attribs & FileAttributes.Normal) == FileAttributes.Normal)
                str.Append('N');
            if ((attribs & FileAttributes.Directory) == FileAttributes.Directory)
                str.Append('D');
            if ((attribs & FileAttributes.Offline) == FileAttributes.Offline)
                str.Append('O');
            if ((attribs & FileAttributes.Compressed) == FileAttributes.Compressed)
                str.Append('C');
            if ((attribs & FileAttributes.Temporary) == FileAttributes.Temporary)
                str.Append('T');

            return str.ToString();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            FileInfo fi = new FileInfo(this.openFileDialog1.FileName);
            FileAttributes fa = new FileAttributes();

            foreach(object o in this.chkListFileAttributes.CheckedItems)
            {
                fa = fa | (FileAttributes)(Enum)o;
            }

            try
            {
                if(fi.IsReadOnly) fi.IsReadOnly = false;
                fi.CreationTime = DateTime.Parse(this.txtCreationTime.Text);
                fi.LastAccessTime = DateTime.Parse(this.txtLastAccessTime.Text);
                fi.LastWriteTime = DateTime.Parse(this.txtLastWriteTime.Text);

                fi.Attributes = fa;
                getFileInfo(fi);

            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #9
0
 public void WriteAllBytes(string path, byte[] bytes, FileAttributes attributes)
 {
     if (File.Exists(path))
         File.SetAttributes(path, FileAttributes.Normal);
     File.WriteAllBytes(path, bytes);
     File.SetAttributes(path, attributes);
 }
Example #10
0
        public BackupHandler(string backendurl, Options options, BackupResults results)
        {
            EMPTY_METADATA = Utility.WrapMetadata(new Dictionary<string, string>(), options);

            m_options = options;
            m_result = results;
            m_backendurl = backendurl;

            m_attributeFilter = m_options.FileAttributeFilter;
            m_symlinkPolicy = m_options.SymlinkPolicy;
            m_blocksize = m_options.Blocksize;

            m_blockbuffer = new byte[m_options.Blocksize * Math.Max(1, m_options.FileReadBufferSize / m_options.Blocksize)];
            m_blocklistbuffer = new byte[m_options.Blocksize];

            m_blockhasher = System.Security.Cryptography.HashAlgorithm.Create(m_options.BlockHashAlgorithm);
            m_filehasher = System.Security.Cryptography.HashAlgorithm.Create(m_options.FileHashAlgorithm);

            if (m_blockhasher == null)
                throw new Exception(string.Format(Strings.Foresthash.InvalidHashAlgorithm, m_options.BlockHashAlgorithm));
            if (m_filehasher == null)
                throw new Exception(string.Format(Strings.Foresthash.InvalidHashAlgorithm, m_options.FileHashAlgorithm));

            if (!m_blockhasher.CanReuseTransform)
                throw new Exception(string.Format(Strings.Foresthash.InvalidCryptoSystem, m_options.BlockHashAlgorithm));
            if (!m_filehasher.CanReuseTransform)
                throw new Exception(string.Format(Strings.Foresthash.InvalidCryptoSystem, m_options.FileHashAlgorithm));

            if (options.AllowPassphraseChange)
                throw new Exception(Strings.Foresthash.PassphraseChangeUnsupported);
        }
Example #11
0
 public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
 {
     string path = GetTestFileName();
     DirectoryInfo testDir = Directory.CreateDirectory(Path.Combine(TestDirectory, path));
     testDir.Attributes = attributes;
     Assert.Equal(testDir.FullName, new DirectoryInfo(TestDirectory).CreateSubdirectory(path).FullName);
 }
Example #12
0
 public void UnixInvalidAttributes(FileAttributes attr)
 {
     var path = GetTestFilePath();
     File.Create(path).Dispose();
     Set(path, attr);
     Assert.Equal(FileAttributes.Normal, Get(path));
 }
 public LoadFileConfiguration(string sourceFile, string targetFile,
     FileAttributes targetFileAttributes = FileAttributes.Normal)
 {
     SourceFile = sourceFile;
     TargetFile = targetFile;
     TargetFileAttributes = targetFileAttributes;
 }
Example #14
0
        public static Stream CreateFile(
            string fileName, FileAccess fileAccess, FileShare fileShare, FileMode fileMode, FileAttributes flags)
        {
            // TODO: This is not quite right, but it's close.
            //
            var nativeAccess = fileAccess;
            if ((nativeAccess & FileAccess.Read) != 0)
            {
                nativeAccess &= ~FileAccess.Read;
                nativeAccess |= (FileAccess)GENERIC_READ;
            }
            if ((nativeAccess & FileAccess.Write) != 0)
            {
                nativeAccess &= ~FileAccess.Write;
                nativeAccess |= (FileAccess)GENERIC_WRITE;
            }

            var handle = _CreateFile(fileName, nativeAccess, fileShare, IntPtr.Zero, fileMode, flags, IntPtr.Zero);
            if (handle.IsInvalid)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            return new SimpleFileStream(handle);
        }
Example #15
0
        public DokanError CreateFile(string fileName, DokanNet.FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, DokanFileInfo info)
        {
            info.DeleteOnClose = (options & FileOptions.DeleteOnClose) != 0;
            //Console.WriteLine("CreateFile: {0}, mode = {1}", fileName, mode);

            if (fileName == "\\")
            {
                return DokanError.ErrorSuccess;
            }

            Directory dir = new Directory(Util.GetPathDirectory(fileName));
            if (!dir.Exists())
            {
                return DokanError.ErrorPathNotFound;
            }

            String name = Util.GetPathFileName(fileName);

            if (name.Length == 0)
            {
                return DokanError.ErrorInvalidName;
            }
            if (name.IndexOfAny(Path.GetInvalidFileNameChars()) > -1)
            {
                return DokanError.ErrorInvalidName;
            }

            // dokan API 要求在目标文件是目录时候,设置 info.IsDirectory = true
            if (dir.Contains(name) && (dir.GetItemInfo(name).attribute & FileAttributes.Directory) != 0)
            {
                info.IsDirectory = true;
                return DokanError.ErrorSuccess;
            }

            try
            {
                File f = new File(fileName, mode);
                f.flagDeleteOnClose = info.DeleteOnClose;
                info.Context = f;
            }
            catch (FileNotFoundException)
            {
                return DokanError.ErrorFileNotFound;
            }
            catch (IOException)
            {
                return DokanError.ErrorAlreadyExists;
            }
            catch (NotImplementedException)
            {
                return DokanError.ErrorAccessDenied;
            }
            catch (Exception)
            {
                return DokanError.ErrorError;
            }

            return DokanError.ErrorSuccess;
        }
 /// <summary>
 /// Creates an instance of <see cref = "QuickIOFileSystemEntry"/>
 /// </summary>
 internal QuickIOFileSystemEntry( string path, QuickIOFileSystemEntryType type, FileAttributes  attributes, ulong bytes)
 {
     Contract.Requires( !string.IsNullOrWhiteSpace( path ) );
     Path = path;
     Type = type;
     Attributes = attributes;
     Bytes = bytes;
 }
Example #17
0
 public static Boolean IsSet(this FileAttributes flags, FileAttributes flagToTest)
 {
     if (flagToTest == 0)
     {
         throw new ArgumentOutOfRangeException("flagToTest", "Value must not be 0");
     }
     return (flags & flagToTest) == flagToTest;
 }
Example #18
0
 public static void ApplyAttributes(this FileInfo fileInfo, FileAttributes attributes)
 {
     FileAttributes currentAttributes = fileInfo.Attributes;
     if ((currentAttributes & attributes) != attributes)
     {
         fileInfo.Attributes = (fileInfo.Attributes | attributes);
     }
 }
Example #19
0
 public void WindowsAttributeSetting(FileAttributes attr)
 {
     var test = new DirectoryInfo(GetTestFilePath());
     test.Create();
     Set(test.FullName, attr);
     Assert.Equal(attr | FileAttributes.Directory, Get(test.FullName));
     Set(test.FullName, 0);
 }
Example #20
0
 public void WindowsAttributeSetting(FileAttributes attr)
 {
     var path = GetTestFilePath();
     File.Create(path).Dispose();
     Set(path, attr);
     Assert.Equal(attr, Get(path));
     Set(path, 0);
 }
Example #21
0
 /// <summary>
 /// Attempts to clear the specified attribute(s) on the given path.
 /// </summary>
 public static void ClearAttributes(this IFileService fileService, string path, FileAttributes attributes)
 {
     FileAttributes currentAttributes = fileService.GetAttributes(path);
     if ((currentAttributes & attributes) != 0)
     {
         fileService.SetAttributes(path, currentAttributes &= ~attributes);
     }
 }
 /// <summary>
 /// Walk directories in the current directory. Allows filtering by attributes. Folders with the given attributes will be skipped as well.
 /// </summary>
 /// <param name="fileSystemInformation">If the information is not a directory, returns an empty enumerable.</param>
 public static IEnumerable<IDirectoryInformation> EnumerateDirectories(
     this IDirectoryInformation directoryInformation,
     string searchPattern = "*",
     SearchOption searchOption = SearchOption.TopDirectoryOnly,
     FileAttributes excludeAttributes = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint)
 {
     return directoryInformation.EnumerateChildren(ChildType.Directory, searchPattern, searchOption, excludeAttributes).OfType<IDirectoryInformation>();
 }
 public static void RemoveAttribute(string filePath, FileAttributes attributes, FileAttributes attributesToRemove)
 {
     //if it has the attribute to remove then remove it
     if ((attributes & attributesToRemove) == attributesToRemove)
     {
         File.SetAttributes(filePath, attributes & ~attributesToRemove);
     }
 }
Example #24
0
 /// <summary>
 ///     Adds a file attribute
 /// </summary>
 /// <param name="pathInfo">Affected target</param>
 /// <param name="attribute">Attribute to add</param>
 /// <returns>true if added. false if already exists in attributes</returns>
 public static Boolean AddAttribute(PathInfo pathInfo, FileAttributes attribute)
 {
     if ((pathInfo.Attributes & attribute) == attribute) { return false; }
     var attributes = pathInfo.Attributes;
     attributes |= attribute;
     SetAttributes(pathInfo, attributes);
     return true;
 }
Example #25
0
 protected override void SetUp() {
     base.SetUp();
     _tempFileName = Path.Combine(TempDirName, "myfile.txt");
     TempFile.Create(_tempFileName);
     File.SetAttributes(_tempFileName, FileAttributes.Normal);
     // Handle case when temp folder is compressed
     _normalFileAttributes = File.GetAttributes(_tempFileName) & (FileAttributes.Normal | FileAttributes.Compressed);
 }
Example #26
0
        public static FileAttributes UnPack(long fa)
        {
            FileAttributes f = new FileAttributes();

            if ((fa & Directory) > 0)	f |= FileAttributes.Directory;

            return f;
        }
Example #27
0
		internal static void SetAttributes(string path, FileAttributes fileAttributes)
		{
			string normalizedPath = Path.NormalizeLongPath(path);
			if (!NativeMethods.SetFileAttributes(normalizedPath, fileAttributes))
			{
				throw GetExceptionFromLastWin32Error();
			}
		}
Example #28
0
 public DirDir(DirectoryInfo dir)
 {
     Name = dir.Name;
     FullPath = dir.FullName;
     Parent = dir.Parent;
     Created = dir.CreationTime;
     Attributes = dir.Attributes;
 }
 public void NewItem(string folderName, string name, FileAttributes attrs)
 {
     ThrowIfDisposed();
     using (ComReleaser<IShellItem> folderItem = CreateShellItem(folderName))
     {
         _fileOperation.NewItem(folderItem.Item, attrs, name, string.Empty, _callbackSink);
     }
 }
Example #30
0
 /// <inheritdoc cref="File.SetAttributes"/>
 public abstract void SetAttributes(string path, FileAttributes fileAttributes);
Example #31
0
 private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
 {
     return(attributes & ~attributesToRemove);
 }
Example #32
0
        public bool MoveNext()
        {
            if (_lastEntryFound)
            {
                return(false);
            }

            FileSystemEntry entry = default;

            lock (_lock)
            {
                if (_lastEntryFound)
                {
                    return(false);

                    // If HAVE_READDIR_R is defined for the platform FindNextEntry depends on _entryBuffer being fixed since
                    // _entry will point to a string in the middle of the array. If the array is not fixed GC can move it after
                    // the native call and _entry will point to a bogus file name.
                    fixed(byte *entryBufferPtr = _entryBuffer)
                    {
                        do
                        {
                            FindNextEntry(entryBufferPtr, _entryBuffer == null ? 0 : _entryBuffer.Length);
                            if (_lastEntryFound)
                            {
                                return(false);
                            }

                            FileAttributes attributes = FileSystemEntry.Initialize(
                                ref entry, _entry, _currentPath, _rootDirectory, _originalRootDirectory, new Span <char>(_pathBuffer));
                            bool isDirectory = (attributes & FileAttributes.Directory) != 0;

                            bool isSpecialDirectory = false;
                            if (isDirectory)
                            {
                                // Subdirectory found
                                if (_entry.Name[0] == '.' && (_entry.Name[1] == 0 || (_entry.Name[1] == '.' && _entry.Name[2] == 0)))
                                {
                                    // "." or "..", don't process unless the option is set
                                    if (!_options.ReturnSpecialDirectories)
                                    {
                                        continue;
                                    }
                                    isSpecialDirectory = true;
                                }
                            }

                            if (!isSpecialDirectory && _options.AttributesToSkip != 0)
                            {
                                if ((_options.AttributesToSkip & FileAttributes.ReadOnly) != 0)
                                {
                                    // ReadOnly is the only attribute that requires hitting entry.Attributes (which hits the disk)
                                    attributes = entry.Attributes;
                                }

                                if ((_options.AttributesToSkip & attributes) != 0)
                                {
                                    continue;
                                }
                            }

                            if (isDirectory && !isSpecialDirectory)
                            {
                                if (_options.RecurseSubdirectories && ShouldRecurseIntoEntry(ref entry))
                                {
                                    // Recursion is on and the directory was accepted, Queue it
                                    if (_pending == null)
                                    {
                                        _pending = new Queue <string>();
                                    }
                                    _pending.Enqueue(Path.Join(_currentPath, entry.FileName));
                                }
                            }

                            if (ShouldIncludeEntry(ref entry))
                            {
                                _current = TransformEntry(ref entry);
                                return(true);
                            }
                        } while (true);
                    }
            }
        }
Example #33
0
        public async Task Configure(string connectionString, string image, string hostname, string deviceCaCert, string deviceCaPk, string deviceCaCerts)
        {
            Console.WriteLine($"Setting up iotedged with agent image '{image}'");

            const string  YamlPath = "/etc/iotedge/config.yaml";
            Task <string> text     = File.ReadAllTextAsync(YamlPath);

            var doc = new YamlDocument(await text);

            doc.ReplaceOrAdd("provisioning.device_connection_string", connectionString);
            doc.ReplaceOrAdd("agent.config.image", image);
            doc.ReplaceOrAdd("hostname", hostname);

            foreach (RegistryCredentials c in this.credentials)
            {
                doc.ReplaceOrAdd("agent.config.auth.serveraddress", c.Address);
                doc.ReplaceOrAdd("agent.config.auth.username", c.User);
                doc.ReplaceOrAdd("agent.config.auth.password", c.Password);
            }

            if (this.httpUris.HasValue)
            {
                HttpUris uris = this.httpUris.OrDefault();
                doc.ReplaceOrAdd("connect.management_uri", uris.ConnectManagement);
                doc.ReplaceOrAdd("connect.workload_uri", uris.ConnectWorkload);
                doc.ReplaceOrAdd("listen.management_uri", uris.ListenManagement);
                doc.ReplaceOrAdd("listen.workload_uri", uris.ListenWorkload);
            }
            else
            {
                doc.ReplaceOrAdd("connect.management_uri", "unix:///var/run/iotedge/mgmt.sock");
                doc.ReplaceOrAdd("connect.workload_uri", "unix:///var/run/iotedge/workload.sock");
                doc.ReplaceOrAdd("listen.management_uri", "fd://iotedge.mgmt.socket");
                doc.ReplaceOrAdd("listen.workload_uri", "fd://iotedge.socket");
            }

            if (!string.IsNullOrEmpty(deviceCaCert) && !string.IsNullOrEmpty(deviceCaPk) && !string.IsNullOrEmpty(deviceCaCerts))
            {
                doc.ReplaceOrAdd("certificates.device_ca_cert", deviceCaCert);
                doc.ReplaceOrAdd("certificates.device_ca_pk", deviceCaPk);
                doc.ReplaceOrAdd("certificates.trusted_ca_certs", deviceCaCerts);
            }

            string result = doc.ToString();


            FileAttributes attr = 0;

            if (File.Exists(YamlPath))
            {
                attr = File.GetAttributes(YamlPath);
                File.SetAttributes(YamlPath, attr & ~FileAttributes.ReadOnly);
            }

            await File.WriteAllTextAsync(YamlPath, result);

            if (attr != 0)
            {
                File.SetAttributes(YamlPath, attr);
            }
        }
        // Copy over all the attributes you would want copied from a template file.
        // As of right now this is just acl's
        private void DuplicateTemplateAttributes(string source, string destination)
        {
            FileAttributes fileAttributes = File.GetAttributes(source);

            File.SetAttributes(destination, fileAttributes);
        }
Example #35
0
        bool IsSymlink(string file)
        {
            FileAttributes attributes = File.GetAttributes(file);

            return((attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint);
        }
Example #36
0
        public async Task LoadAsync(Type[] types = null)
        {
            SyntaxTree[] syntaxTrees;

            FileAttributes fileAttr = File.GetAttributes(PathLocation);

            if (fileAttr.HasFlag(FileAttributes.Directory))
            {
                syntaxTrees = (await LoadSyntaxTreeFolderAsync(PathLocation)).ToArray();
            }
            else
            {
                syntaxTrees = new SyntaxTree[] { await LoadSyntaxTreeAsync(PathLocation) }
            };

            var callerAssembly = Assembly.GetEntryAssembly();

            ClientHelper.ActHelper.Commands = callerAssembly.GetType("Commands");

            var locationNetCore = typeof(System.Net.Http.HttpClient).Assembly.Location;

            var pathNetCore = @"C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.1.0\ref\netcoreapp2.1";

            var directoryInfo = new DirectoryInfo(pathNetCore);

            FileInfo[] files = directoryInfo.GetFiles("*.dll");

            List <MetadataReference> metadataReferences = new List <MetadataReference>();

            foreach (var file in files)
            {
                metadataReferences.Add(MetadataReference.CreateFromFile(file.FullName));
            }

            metadataReferences.Add(MetadataReference.CreateFromFile(typeof(CSNS.ClientHelper.ActHelper).Assembly.Location));
            metadataReferences.Add(MetadataReference.CreateFromFile(typeof(Newtonsoft.Json.JsonConvert).Assembly.Location));

            //Next work, try to think a way to run References from outside.
            var compilation = CSharpCompilation.Create($"{AssemblyName}.dll", syntaxTrees, metadataReferences, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));



            using (MemoryStream memoryStream = new MemoryStream())
            {
                var result = compilation.Emit(memoryStream);

                if (!result.Success)
                {
                    var diagnostics = result.Diagnostics.Where(obj => obj.Severity == DiagnosticSeverity.Error);

                    if (diagnostics.Any())
                    {
                        var error = string.Join(" \n", diagnostics.Select(a => $"{a.WarningLevel.ToString()} - {a.GetMessage()}"));
                        throw new Exception(error);
                    }
                }

                memoryStream.Seek(0, SeekOrigin.Begin);

                Assembly = ReloadAssembly(memoryStream);
            }

            CSNSStaticLoader.LoadCode(Assembly);
        }
Example #37
0
 public static bool IsHidden(FileAttributes fileAttributes)
 {
     return((fileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden);
 }
Example #38
0
 public void SetAttributes(string path, FileAttributes fileAttributes) => Alphaleonis.Win32.Filesystem.File.SetAttributes(path, fileAttributes);
Example #39
0
 public void SetAttributes(string path, FileAttributes fileAttributes) => File.SetAttributes(path, fileAttributes);
Example #40
0
 /// <remarks>
 /// No implementation needed because this provider doesn't support FileAttributes.
 /// </remarks>
 public override void SetFileAttributes(IFileInfo file, FileAttributes fileAttributes)
 {
 }
Example #41
0
 public override void SetAttributes(FileAttributes attributes)
 {
     Utils.SetFileInformationToFileStream(Stream, attributes, null, null, null);
 }
Example #42
0
        // Insert logic for processing found files here.
        private void ProcessFile(string path, ProcessType processType)
        {
            DateTime lastWrite = File.GetLastWriteTime(path);

            if (processType == ProcessType.Organise)
            {
                //if year folder does not exist
                if (!Directory.Exists(folder_name.Text + "/" + lastWrite.Year.ToString()))
                {
                    Directory.CreateDirectory(folder_name.Text + "/" + lastWrite.Year.ToString());
                }
                PathsToNotMove.Add(folder_name.Text + "/" + lastWrite.Year.ToString());


                if (!Directory.Exists(folder_name.Text +
                                      "/" + lastWrite.Year.ToString() +
                                      "/" + lastWrite.Month.ToString() + " - " + lastWrite.ToString("MMMM")))
                {
                    Directory.CreateDirectory(folder_name.Text +
                                              "/" + lastWrite.Year.ToString() +
                                              "/" + lastWrite.Month.ToString() + " - " + lastWrite.ToString("MMMM"));
                }
                PathsToNotMove.Add(folder_name.Text +
                                   "/" + lastWrite.Year.ToString() +
                                   "/" + lastWrite.Month.ToString() + " - " + lastWrite.ToString("MMMM"));
            }
            else
            {
                if (!PathsToNotMove.Contains(path))
                {
                    // get the file attributes for file or directory
                    FileAttributes attr = File.GetAttributes(path);

                    if (attr.HasFlag(FileAttributes.Directory))
                    {
                        String PathToMove = folder_name.Text +
                                            "/" + lastWrite.Year.ToString() +
                                            "/" + lastWrite.Month.ToString() + " - " + lastWrite.ToString("MMMM");

                        if (int.TryParse(Path.GetFileNameWithoutExtension(path), out int year))
                        {
                            if (year > DateTime.Now.Year && year < 1900)
                            {
                                Console.WriteLine(PathToMove + "\\" + Path.GetFileNameWithoutExtension(path));
                                Directory.Move(path, PathToMove + "\\" + Path.GetFileNameWithoutExtension(path));
                            }
                        }
                        else
                        {
                            try
                            {
                                Directory.Move(path, PathToMove + "\\" + Path.GetFileNameWithoutExtension(path));
                            }
                            catch (Exception ex) {
                                System.Windows.MessageBox.Show(path, PathToMove + "\\" + Path.GetFileNameWithoutExtension(path));
                            }
                        }
                    }
                    else
                    {
                        int count = 1;
                        while (true)
                        {
                            try
                            {
                                if (count == 1)
                                {
                                    File.Move(path, folder_name.Text +
                                              "/" + lastWrite.Year.ToString() +
                                              "/" + lastWrite.Month.ToString() + " - " + lastWrite.ToString("MMMM") +
                                              "/" + Path.GetFileName(path));
                                }
                                else
                                {
                                    File.Move(path, folder_name.Text +
                                              "/" + lastWrite.Year.ToString() +
                                              "/" + lastWrite.Month.ToString() + " - " + lastWrite.ToString("MMMM") +
                                              "/" + count.ToString() + "_" + Path.GetFileName(path));
                                }


                                break;
                            }
                            catch
                            {
                                count++;
                            }
                        }
                    }
                }
            }
        }
Example #43
0
 public override void SetAttributes(string fullPath, FileAttributes attributes)
 {
     new FileInfo(fullPath, null).Attributes = attributes;
 }
        /// <summary>
        /// Apply the changes
        /// </summary>
        /// <param name="sender">object sender</param>
        /// <param name="e">event arguments</param>
        /// <remarks>The parameters <paramref name="e"/> and <paramref name="sender"/> are not needed, but must be indicated.</remarks>
        private void ButtonApply_Click(object sender, EventArgs e)
        {
            DateTime       creationTime   = dateTimePickerWrited.Value;
            DateTime       lastAccessTime = dateTimePickerWrited.Value;
            DateTime       lastWriteTime  = dateTimePickerWrited.Value;
            FileAttributes attr           = File.GetAttributes(path: textBoxPath.Text);
            bool           isFolder       = (attr & FileAttributes.Directory) == FileAttributes.Directory;

            if (dateTimePickerCreated.Checked)
            {
                if (isFolder)
                {
                    Directory.SetCreationTime(path: textBoxPath.Text, creationTime: creationTime);
                }
                else
                {
                    File.SetCreationTime(path: textBoxPath.Text, creationTime: creationTime);
                }
            }
            if (dateTimePickerAccessed.Checked)
            {
                if (isFolder)
                {
                    Directory.SetLastAccessTime(path: textBoxPath.Text, lastAccessTime: lastAccessTime);
                }
                else
                {
                    File.SetLastAccessTime(path: textBoxPath.Text, lastAccessTime: lastAccessTime);
                }
            }
            if (dateTimePickerWrited.Checked)
            {
                if (isFolder)
                {
                    Directory.SetLastWriteTime(path: textBoxPath.Text, lastWriteTime: lastWriteTime);
                }
                else
                {
                    File.SetLastWriteTime(path: textBoxPath.Text, lastWriteTime: lastWriteTime);
                }
            }
            radioButtonCreationDateLocalTime.Checked   = radioButtonNewCreationDateLocalTime.Checked;
            radioButtonCreationDateUtc.Checked         = radioButtonNewCreationDateUtc.Checked;
            radioButtonLastAccessDateLocalTime.Checked = radioButtonNewLastAccessDateLocalTime.Checked;
            radioButtonLastAccessDateUtc.Checked       = radioButtonNewLastAccessDateUtc.Checked;
            radioButtonLastWriteDateLocalTime.Checked  = radioButtonNewLastWriteDateLocalTime.Checked;
            radioButtonLastWriteDateUtc.Checked        = radioButtonNewLastWriteDateUtc.Checked;
            textBoxCreationDate.Text = radioButtonCreationDateLocalTime.Checked
                                ? isFolder
                                        ? Directory.GetCreationTime(path: textBoxPath.Text).ToString(provider: culture)
                                        : File.GetCreationTime(path: textBoxPath.Text).ToString(provider: culture)
                                : isFolder
                                        ? Directory.GetCreationTimeUtc(path : textBoxPath.Text).ToString(provider: culture)
                                        : File.GetCreationTimeUtc(path: textBoxPath.Text).ToString(provider: culture);

            textBoxLastAccessDate.Text = radioButtonLastAccessDateLocalTime.Checked
                                ? isFolder
                                        ? Directory.GetLastAccessTime(path: textBoxPath.Text).ToString(provider: culture)
                                        : File.GetLastAccessTime(path: textBoxPath.Text).ToString(provider: culture)
                                : isFolder
                                        ? Directory.GetLastAccessTimeUtc(path : textBoxPath.Text).ToString(provider: culture)
                                        : File.GetLastAccessTimeUtc(path: textBoxPath.Text).ToString(provider: culture);

            textBoxLastWriteDate.Text = radioButtonLastWriteDateLocalTime.Checked
                                ? isFolder
                                        ? Directory.GetLastWriteTime(path: textBoxPath.Text).ToString(provider: culture)
                                        : File.GetLastWriteTime(path: textBoxPath.Text).ToString(provider: culture)
                                : isFolder
                                        ? Directory.GetLastWriteTimeUtc(path : textBoxPath.Text).ToString(provider: culture)
                                        : File.GetLastWriteTimeUtc(path: textBoxPath.Text).ToString(provider: culture);

            MessageBox.Show(text: StringResources.allDataChanged, caption: StringResources.information, buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
        }
 public virtual void SetAttributes(string path, FileAttributes fileAttributes)
 {
     File.SetAttributes(path, fileAttributes);
 }
Example #46
0
 public static extern IntPtr CreateFile(string lpFileName,
                                        FileAccess dwDesiredAccess, uint dwShareMode,
                                        IntPtr lpSecurityAttributes, CreationDisposition dwCreationDisposition,
                                        FileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile);
Example #47
0
 protected static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
 {
     return(attributes & ~attributesToRemove);
 }
Example #48
0
 public override void SetAttributes(string fullPath, FileAttributes attributes)
 {
     SetAttributesInternal(fullPath, attributes);
 }
        /// <summary>
        /// Upload local pictures to azure storage.
        ///   1. Upload png files starting with "azure" in the source directory as block blobs, not including the sub-directory.
        ///   2. Store source file's file attributes and permissions into destination blob's meta data.
        ///   3. Download png files starting with "azure" in the source directory to a local directory, not including the sub-directory.
        ///   4. Restore file attributes and permissions to destination local file.
        /// </summary>
        private static async Task BlobDirectoryPreserveFilePropertiesSampleAsync()
        {
            //Enable required privileges before getting/setting permissions from/to local file system.
            FileSecurityOperations.EnableRequiredPrivileges(PreserveSMBPermissions.Owner | PreserveSMBPermissions.Group | PreserveSMBPermissions.DACL | PreserveSMBPermissions.SACL, true);

            try
            {
                string             sourceDirPath = ".";
                CloudBlobDirectory destDir       = await Util.GetCloudBlobDirectoryAsync(ContainerName, "blobdir");

                // SearchPattern and Recuresive can be used to determine the files to be transferred from the source directory. The behavior of
                // SearchPattern and Recuresive varies for different source directory types.
                // See https://azure.github.io/azure-storage-net-data-movement for more details.
                //
                // When source is local directory, data movement library matches source files against the SearchPattern as standard wildcards. If
                // recuresive is set to false, only files directly under the source directory will be matched. Otherwise, all files in the
                // sub-directory will be matched as well.
                //
                // In the following case, data movement library will upload png files starting with "azure" in the source directory as block blobs,
                // not including the sub-directory.
                UploadDirectoryOptions options = new UploadDirectoryOptions()
                {
                    SearchPattern = "azure*.png",
                    Recursive     = false,
                    BlobType      = BlobType.BlockBlob
                };

                DirectoryTransferContext context = new DirectoryTransferContext();

                // Register for transfer event.
                context.FileTransferred += FileTransferredCallback;
                context.FileFailed      += FileFailedCallback;
                context.FileSkipped     += FileSkippedCallback;

                context.SetAttributesCallbackAsync = async(sourceObj, destination) =>
                {
                    string         sourcePath     = sourceObj as string;
                    DateTimeOffset?creationTime   = null;
                    DateTimeOffset?lastWriteTime  = null;
                    FileAttributes?fileAttributes = null;

                    FileOperations.GetFileProperties(sourcePath, out creationTime, out lastWriteTime, out fileAttributes);

                    string sourceFileSDDL = FileSecurityOperations.GetFilePortableSDDL(sourcePath,
                                                                                       PreserveSMBPermissions.Owner | PreserveSMBPermissions.Group | PreserveSMBPermissions.DACL | PreserveSMBPermissions.SACL);

                    CloudBlob destBlob = destination as CloudBlob;

                    // Blob's original meta data has already been gotten from azure storage by DataMovement Library,
                    // Here only need to add new meta data key-value pairs, DataMovement Library will set these value to destination blob later.
                    destBlob.Metadata.Add(CreationTimeName, creationTime.Value.ToString());
                    destBlob.Metadata.Add(LastWriteTimeName, lastWriteTime.Value.ToString());
                    destBlob.Metadata.Add(FileAttributesName, fileAttributes.Value.ToString());
                    destBlob.Metadata.Add(FilePermissionsName, sourceFileSDDL);
                };

                context.ShouldTransferCallbackAsync = async(source, destination) =>
                {
                    // Can add more logic here to evaluate whether really need to transfer the target.
                    return(true);
                };

                TransferStatus trasferStatus =
                    await TransferManager.UploadDirectoryAsync(sourceDirPath, destDir, options, context);


                Console.WriteLine("Final transfer state: {0}", TransferStatusToString(trasferStatus));
                Console.WriteLine("Files in directory {0} uploading to {1} is finished.", sourceDirPath, destDir.Uri.ToString());

                //Next the sample will show how to download a directory and restore file attributes to local file.
                string             destDirPath = ".";
                CloudBlobDirectory sourceDir   = await Util.GetCloudBlobDirectoryAsync(ContainerName, "blobdir");

                // In the following case, data movement library will download file named "azure.png" in the source directory,
                // not including the sub-directory.
                DownloadDirectoryOptions downloadDirectoryOptions = new DownloadDirectoryOptions()
                {
                    SearchPattern = "azure.png",
                    Recursive     = false
                };

                DirectoryTransferContext directoryTransferContext = new DirectoryTransferContext();
                // Register for transfer event.
                directoryTransferContext.FileFailed  += FileFailedCallback;
                directoryTransferContext.FileSkipped += FileSkippedCallback;

                //Get stored file properties from source blob meta data and set to local file.
                directoryTransferContext.FileTransferred += (object sender, TransferEventArgs e) =>
                {
                    CloudBlob sourceBlob   = e.Source as CloudBlob;
                    string    destFilePath = e.Destination as string;

                    string         metadataValue  = null;
                    DateTimeOffset creationTime   = default(DateTimeOffset);
                    DateTimeOffset lastWriteTime  = default(DateTimeOffset);
                    FileAttributes fileAttributes = default(FileAttributes);

                    bool gotCreationTime   = false;
                    bool gotLastWriteTime  = false;
                    bool gotFileAttributes = false;

                    if (sourceBlob.Metadata.TryGetValue(CreationTimeName, out metadataValue) &&
                        !string.IsNullOrEmpty(metadataValue))
                    {
                        gotCreationTime = DateTimeOffset.TryParse(metadataValue, out creationTime);
                    }

                    if (sourceBlob.Metadata.TryGetValue(LastWriteTimeName, out metadataValue) &&
                        !string.IsNullOrEmpty(metadataValue))
                    {
                        gotLastWriteTime = DateTimeOffset.TryParse(metadataValue, out lastWriteTime);
                    }

                    if (sourceBlob.Metadata.TryGetValue(FileAttributesName, out metadataValue) &&
                        !string.IsNullOrEmpty(metadataValue))
                    {
                        gotFileAttributes = Enum.TryParse <FileAttributes>(metadataValue, out fileAttributes);
                    }

                    if (gotCreationTime && gotLastWriteTime && gotFileAttributes)
                    {
                        FileOperations.SetFileProperties(destFilePath, creationTime, lastWriteTime, fileAttributes);
                    }

                    if (sourceBlob.Metadata.TryGetValue(FilePermissionsName, out metadataValue) &&
                        !string.IsNullOrEmpty(metadataValue))
                    {
                        FileSecurityOperations.SetFileSecurity(destFilePath, metadataValue,
                                                               PreserveSMBPermissions.Owner | PreserveSMBPermissions.Group | PreserveSMBPermissions.DACL | PreserveSMBPermissions.SACL);
                    }
                };

                // Always writes to destination no matter it exists or not.
                directoryTransferContext.ShouldOverwriteCallbackAsync = TransferContext.ForceOverwrite;

                trasferStatus =
                    await TransferManager.DownloadDirectoryAsync(sourceDir, destDirPath, downloadDirectoryOptions, directoryTransferContext);


                Console.WriteLine("Final transfer state: {0}", TransferStatusToString(trasferStatus));
                Console.WriteLine("Files in directory {0} downloading to {1} is finished.", sourceDir.Uri.ToString(), destDirPath);
            }
            finally
            {
                //Restore privileges after getting/setting permissions from/to local file system.
                FileSecurityOperations.RestorePrivileges(PreserveSMBPermissions.Owner | PreserveSMBPermissions.Group | PreserveSMBPermissions.DACL | PreserveSMBPermissions.SACL, true);
            }
        }
 public int SetFileAttributes(string filename, FileAttributes attr, DokanFileInfo info)
 {
     Trace.WriteLine(string.Format("SetFileAttributes {0}", filename));
     return(0);
 }
Example #51
0
        public void SetAttributes(string path, FileAttributes attributes)
        {
            // Validate that only flags from the attribute are being provided.  This is an
            // approximation for the validation done by the Win32 function.
            const FileAttributes allValidFlags =
                FileAttributes.Archive | FileAttributes.Compressed | FileAttributes.Device |
                FileAttributes.Directory | FileAttributes.Encrypted | FileAttributes.Hidden |
                FileAttributes.IntegrityStream | FileAttributes.Normal | FileAttributes.NoScrubData |
                FileAttributes.NotContentIndexed | FileAttributes.Offline | FileAttributes.ReadOnly |
                FileAttributes.ReparsePoint | FileAttributes.SparseFile | FileAttributes.System |
                FileAttributes.Temporary;
            if ((attributes & ~allValidFlags) != 0)
            {
                // Using constant string for argument to match historical throw
                throw new ArgumentException(SR.Arg_InvalidFileAttrs, "Attributes");
            }

            EnsureStatInitialized(path);

            if (!_exists)
                FileSystemInfo.ThrowNotFound(path);

            if (Interop.Sys.CanSetHiddenFlag)
            {
                if ((attributes & FileAttributes.Hidden) != 0)
                {
                    if ((_fileStatus.UserFlags & (uint)Interop.Sys.UserFlags.UF_HIDDEN) == 0)
                    {
                        // If Hidden flag is set and cached file status does not have the flag set then set it
                        Interop.CheckIo(Interop.Sys.LChflags(path, (_fileStatus.UserFlags | (uint)Interop.Sys.UserFlags.UF_HIDDEN)), path, InitiallyDirectory);
                    }
                }
                else
                {
                    if ((_fileStatus.UserFlags & (uint)Interop.Sys.UserFlags.UF_HIDDEN) == (uint)Interop.Sys.UserFlags.UF_HIDDEN)
                    {
                        // If Hidden flag is not set and cached file status does have the flag set then remove it
                        Interop.CheckIo(Interop.Sys.LChflags(path, (_fileStatus.UserFlags & ~(uint)Interop.Sys.UserFlags.UF_HIDDEN)), path, InitiallyDirectory);
                    }
                }
            }

            // The only thing we can reasonably change is whether the file object is readonly by changing permissions.

            int newMode = _fileStatus.Mode;
            if ((attributes & FileAttributes.ReadOnly) != 0)
            {
                // Take away all write permissions from user/group/everyone
                newMode &= ~(int)(Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IWOTH);
            }
            else if ((newMode & (int)Interop.Sys.Permissions.S_IRUSR) != 0)
            {
                // Give write permission to the owner if the owner has read permission
                newMode |= (int)Interop.Sys.Permissions.S_IWUSR;
            }

            // Change the permissions on the file
            if (newMode != _fileStatus.Mode)
            {
                Interop.CheckIo(Interop.Sys.ChMod(path, newMode), path, InitiallyDirectory);
            }

            _fileStatusInitialized = -1;
        }
Example #52
0
        public NtStatus CreateFile(string fileName, FileAccess access, FileShare share, FileMode mode,
                                   FileOptions options, FileAttributes attributes, IDokanFileInfo info)
        {
            var result   = DokanResult.Success;
            var filePath = GetPath(fileName);

            if (info.IsDirectory)
            {
                try
                {
                    switch (mode)
                    {
                    case FileMode.Open:
                        if (!Directory.Exists(filePath))
                        {
                            try
                            {
                                if (!File.GetAttributes(filePath).HasFlag(FileAttributes.Directory))
                                {
                                    return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
                                                 attributes, DokanResult.NotADirectory));
                                }
                            }
                            catch (Exception)
                            {
                                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
                                             attributes, DokanResult.FileNotFound));
                            }
                            return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
                                         attributes, DokanResult.PathNotFound));
                        }

                        new DirectoryInfo(filePath).EnumerateFileSystemInfos().Any();
                        // you can't list the directory
                        break;

                    case FileMode.CreateNew:
                        if (Directory.Exists(filePath))
                        {
                            return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
                                         attributes, DokanResult.FileExists));
                        }

                        try
                        {
                            File.GetAttributes(filePath).HasFlag(FileAttributes.Directory);
                            return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
                                         attributes, DokanResult.AlreadyExists));
                        }
                        catch (IOException)
                        {
                        }

                        Directory.CreateDirectory(GetPath(fileName));
                        break;
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
                                 DokanResult.AccessDenied));
                }
            }
            else
            {
                var pathExists      = true;
                var pathIsDirectory = false;

                var readWriteAttributes = (access & DataAccess) == 0;
                var readAccess          = (access & DataWriteAccess) == 0;

                try
                {
                    pathExists      = (Directory.Exists(filePath) || File.Exists(filePath));
                    pathIsDirectory = pathExists ? File.GetAttributes(filePath).HasFlag(FileAttributes.Directory) : false;
                }
                catch (IOException)
                {
                }

                switch (mode)
                {
                case FileMode.Open:

                    if (pathExists)
                    {
                        // check if driver only wants to read attributes, security info, or open directory
                        if (readWriteAttributes || pathIsDirectory)
                        {
                            if (pathIsDirectory && (access & FileAccess.Delete) == FileAccess.Delete &&
                                (access & FileAccess.Synchronize) != FileAccess.Synchronize)
                            {
                                //It is a DeleteFile request on a directory
                                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
                                             attributes, DokanResult.AccessDenied));
                            }

                            info.IsDirectory = pathIsDirectory;
                            info.Context     = new object();
                            // must set it to someting if you return DokanError.Success

                            return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
                                         attributes, DokanResult.Success));
                        }
                    }
                    else
                    {
                        return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
                                     DokanResult.FileNotFound));
                    }
                    break;

                case FileMode.CreateNew:
                    if (pathExists)
                    {
                        return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
                                     DokanResult.FileExists));
                    }
                    break;

                case FileMode.Truncate:
                    if (!pathExists)
                    {
                        return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
                                     DokanResult.FileNotFound));
                    }
                    break;
                }

                try
                {
                    info.Context = new FileStream(filePath, mode,
                                                  readAccess ? System.IO.FileAccess.Read : System.IO.FileAccess.ReadWrite, share, 4096, options);

                    if (pathExists && (mode == FileMode.OpenOrCreate ||
                                       mode == FileMode.Create))
                    {
                        result = DokanResult.AlreadyExists;
                    }

                    if (mode == FileMode.CreateNew || mode == FileMode.Create) //Files are always created as Archive
                    {
                        attributes |= FileAttributes.Archive;
                    }
                    File.SetAttributes(filePath, attributes);
                }
                catch (UnauthorizedAccessException) // don't have access rights
                {
                    if (info.Context is FileStream fileStream)
                    {
                        // returning AccessDenied cleanup and close won't be called,
                        // so we have to take care of the stream now
                        fileStream.Dispose();
                        info.Context = null;
                    }
                    return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
                                 DokanResult.AccessDenied));
                }
                catch (DirectoryNotFoundException)
                {
                    return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
                                 DokanResult.PathNotFound));
                }
                catch (Exception ex)
                {
                    var hr = (uint)Marshal.GetHRForException(ex);
                    switch (hr)
                    {
                    case 0x80070020:     //Sharing violation
                        return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
                                     DokanResult.SharingViolation));

                    default:
                        throw;
                    }
                }
            }
            return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
                         result));
        }
Example #53
0
 public static EntryProperties CreateForSuccess(FileAttributes attributes, DateTime creationTimeUtc,
                                                DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc, long fileSize)
 {
     return(new EntryProperties(attributes, creationTimeUtc, lastAccessTimeUtc, lastWriteTimeUtc, fileSize, null));
 }
Example #54
0
        private NtStatus Trace(string method, string fileName, IDokanFileInfo info,
                               FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes,
                               NtStatus result)
        {
#if TRACE
            logger.Debug(
                DokanFormat(
                    $"{method}('{fileName}', {info}, [{access}], [{share}], [{mode}], [{options}], [{attributes}]) -> {result}"));
#endif

            return(result);
        }
Example #55
0
        /// <summary>
        /// Connects the pairs.
        /// </summary>
        public DirectoryFile(FileSystemInfo LocalFile, RemoteFile RemoteFile, DirectoryLogItem LogItem)
        {
            Size = 0;
            if (LocalFile == null)
            {
                Name        = RemoteFile.Name;
                Size        = RemoteFile.Length;
                IsDirectory = RemoteFile.IsDirectory;
            }
            else
            {
                Name = LocalFile.Name;
                FileAttributes attr = File.GetAttributes(LocalFile.FullName);
                IsDirectory = attr.HasFlag(FileAttributes.Directory);
                if (!IsDirectory)
                {
                    Size = new FileInfo(LocalFile.FullName).Length;
                }
            }

            Handle          = SyncHandle.Nothing;
            this.LogItem    = LogItem;
            this.LocalFile  = LocalFile;
            this.RemoteFile = RemoteFile;

            if (LocalFile != null && RemoteFile != null)
            {
                //If file can be found (!)previously & locally & remotely => Find the one with the lastest changes
                if (IsDirectory)
                {
                    Handle = SyncHandle.Synchronize;
                }
                else
                {
                    //Synchronize
                    if (LocalFile.LastWriteTimeUtc.Ticks == LogItem.LocalTicks && RemoteFile.LastWriteTimeUtc.Ticks != LogItem.RemoteTicks)
                    {
                        Handle = SyncHandle.Download;
                    }
                    else if (LocalFile.LastWriteTimeUtc.Ticks != LogItem.LocalTicks && RemoteFile.LastWriteTimeUtc.Ticks == LogItem.RemoteTicks)
                    {
                        Handle = SyncHandle.Upload;
                    }
                    else if (LocalFile.LastWriteTimeUtc.Ticks != LogItem.LocalTicks && RemoteFile.LastWriteTimeUtc.Ticks != LogItem.RemoteTicks)
                    {
                        if (LocalFile.LastWriteTimeUtc.Ticks < RemoteFile.LastWriteTimeUtc.Ticks)
                        {
                            //Download
                            Handle = SyncHandle.Download;
                        }
                        else if (LocalFile.LastWriteTimeUtc.Ticks > RemoteFile.LastWriteTimeUtc.Ticks)
                        {
                            //Upload
                            Handle = SyncHandle.Upload;
                        }
                    }
                }
            }
            else if (LogItem.Equals(DirectoryLogItem.Empty))
            {
                if (LocalFile != null && RemoteFile == null)
                {
                    //If file can be found !previously & locally & !remotely => Upload
                    Handle = SyncHandle.NewUpload;
                }
                else if (LocalFile == null && RemoteFile != null)
                {
                    //If file can be found !previously & !locally & remotely => Download
                    Handle = SyncHandle.NewDownload;
                }
            }
            else
            {
                if (LocalFile != null && RemoteFile == null)
                {
                    //If file can be found previously & locally & !remotely => Delete local (If local & previously LastWriteTime is the same, otherwise upload)
                    if (LocalFile.LastWriteTimeUtc.Ticks == LogItem.LocalTicks)
                    {
                        Handle = SyncHandle.DeleteLocal;
                    }
                    else
                    {
                        Handle = SyncHandle.NewUpload;
                    }
                }
                else if (LocalFile == null && RemoteFile != null)
                {
                    //If file can be found previously & !locally & remotely => Delete remote (If remote & previously LastWriteTime is the same, otherwise download)
                    if (RemoteFile.LastWriteTimeUtc.Ticks == LogItem.RemoteTicks)
                    {
                        Handle = SyncHandle.DeleteRemote;
                    }
                    else
                    {
                        Handle = SyncHandle.NewDownload;
                    }
                }
            }
        }
Example #56
0
 public NtStatus SetFileAttributes(string fileName, FileAttributes attributes, IDokanFileInfo info)
 {
     return(NtStatus.NotImplemented);
 }
Example #57
0
 internal static bool IsDirectory(FileAttributes attributes)
 {
     return((attributes & FileAttributes.Directory) == FileAttributes.Directory);
 }
Example #58
0
        public NtStatus CreateFile(string fileName, DokanNet.FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, IDokanFileInfo info)
        {
            if (mode == FileMode.OpenOrCreate || mode == FileMode.CreateNew || mode == FileMode.Create && Mode == OpenMode.Read)
            {
                return(DokanResult.AccessDenied);
            }

            try
            {
                fileName = FilterPath(fileName);
                bool isDirectory;
                try
                {
                    Fs.GetEntryType(out DirectoryEntryType type, fileName.ToU8Span());
                    isDirectory = type == DirectoryEntryType.Directory;
                }
                catch (DirectoryNotFoundException)
                {
                    return(DokanResult.FileNotFound);
                }

                if (info.IsDirectory || isDirectory)
                {
                    info.IsDirectory = true;
                    if (Fs.FileExists(fileName))
                    {
                        return(DokanResult.NotADirectory);
                    }
                    else if (Fs.DirectoryExists(fileName))
                    {
                        return(DokanResult.Success);
                    }
                    if (mode == FileMode.OpenOrCreate || mode == FileMode.CreateNew || mode == FileMode.Create)
                    {
                        lock (IOLock)
                            Fs.CreateDirectory(fileName.ToU8Span());
                    }
                    else if (mode == FileMode.Open)
                    {
                        return(DokanResult.FileNotFound);
                    }
                }
                else
                {
                    bool exists = Fs.FileExists(fileName);

                    attributes = CreateInfo(fileName).Attributes;

                    if (mode == FileMode.Open && exists)
                    {
                        return(DokanResult.Success);
                    }

                    switch (mode)
                    {
                    case FileMode.Create:
                    case FileMode.OpenOrCreate:
                    case FileMode.CreateNew:
                        if (exists)
                        {
                            return(DokanResult.AlreadyExists);
                        }
                        lock (IOLock)
                            Fs.CreateFile(fileName.ToU8Span(), 0, CreateFileOptions.None);
                        if (Fs.FileExists(fileName))
                        {
                            return(NtStatus.Success);
                        }
                        break;
                    }


                    if (!exists)
                    {
                        return(DokanResult.FileNotFound);
                    }
                }
                return(NtStatus.Success);
            }
            catch (NotImplementedException)
            {
                return(NtStatus.NotImplemented);
            }
        }
Example #59
0
 public static bool IsReadOnly(FileAttributes fileAttributes)
 {
     return((fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
 }