private FileContents ReadFile(FullPath fullName) { try { var fileInfo = new SlimFileInfo(fullName); const int trailingByteCount = 2; var block = NativeFile.ReadFileNulTerminated(fileInfo, trailingByteCount); var contentsByteCount = (int)block.ByteLength - trailingByteCount; // Padding added by ReadFileNulTerminated var kind = NativeMethods.Text_GetKind(block.Pointer, contentsByteCount); switch (kind) { case NativeMethods.TextKind.Ascii: return new AsciiFileContents(new FileContentsMemory(block, 0, contentsByteCount), fileInfo.LastWriteTimeUtc); case NativeMethods.TextKind.AsciiWithUtf8Bom: const int utf8BomSize = 3; return new AsciiFileContents(new FileContentsMemory(block, utf8BomSize, contentsByteCount - utf8BomSize), fileInfo.LastWriteTimeUtc); case NativeMethods.TextKind.Utf8WithBom: var utf16Block = Conversion.UTF8ToUnicode(block); block.Dispose(); return new UTF16FileContents(new FileContentsMemory(utf16Block, 0, utf16Block.ByteLength), fileInfo.LastWriteTimeUtc); case NativeMethods.TextKind.Unknown: default: // TODO(rpaquay): Figure out a better way to detect encoding. //Logger.Log("Text Encoding of file \"{0}\" is not recognized.", fullName); return new AsciiFileContents(new FileContentsMemory(block, 0, contentsByteCount), fileInfo.LastWriteTimeUtc); //throw new NotImplementedException(string.Format("Text Encoding of file \"{0}\" is not recognized.", fullName)); } } catch (Exception e) { Logger.LogException(e, "Error reading content of text file \"{0}\", skipping file.", fullName); return StringFileContents.Empty; } }
public DirectorySnapshot FindRootDirectory(FullPath rootPath) { var index = SortedArrayHelpers.BinarySearch(_snapshot.ProjectRoots, rootPath, ProjectRootComparer); if (index >= 0) return _snapshot.ProjectRoots[index].Directory; return null; }
public DirectoryName CreateAbsoluteDirectoryName(FullPath rootPath) { var rootdirectory = FindRootDirectory(rootPath); if (rootdirectory != null) return rootdirectory.DirectoryName; return _previous.CreateAbsoluteDirectoryName(rootPath); }
private void AddDirectory(FullPath directory) { FileSystemWatcher watcher; lock (_watchersLock) { if (_pollingThread == null) { _pollingThread = new Thread(ThreadLoop) { IsBackground = true }; _pollingThread.Start(); } if (_watchers.TryGetValue(directory, out watcher)) return; watcher = new FileSystemWatcher(); _watchers.Add(directory, watcher); } Logger.LogInfo("Starting monitoring directory \"{0}\" for change notifications.", directory); watcher.Path = directory.Value; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName; watcher.IncludeSubdirectories = true; watcher.InternalBufferSize = 50 * 1024; // 50KB sounds more reasonable than 8KB watcher.Changed += WatcherOnChanged; watcher.Created += WatcherOnCreated; watcher.Deleted += WatcherOnDeleted; watcher.Renamed += WatcherOnRenamed; watcher.Error += WatcherOnError; watcher.EnableRaisingEvents = true; }
private bool FetchRunningDocumentTable() { var rdt = new RunningDocumentTable(_serviceProvider); foreach (var info in rdt) { // Get doc data if (!FullPath.IsValid(info.Moniker)) continue; var path = new FullPath(info.Moniker); if (_openDocuments.ContainsKey(path)) continue; // Get vs buffer IVsTextBuffer docData = null; try { docData = info.DocData as IVsTextBuffer; } catch (Exception e) { Logger.LogWarning(e, "Error getting IVsTextBuffer for document {0}, skipping document", path); } if (docData == null) continue; // Get ITextDocument var textBuffer = _vsEditorAdaptersFactoryService.GetDocumentBuffer(docData); if (textBuffer == null) continue; ITextDocument document; if (!_textDocumentFactoryService.TryGetTextDocument(textBuffer, out document)) continue; _openDocuments[path] = document; } return true; }
public PathChangeKind GetPathChangeKind(FullPath path) { PathChangeKind result; if (!_map.Value.TryGetValue(path, out result)) { result = PathChangeKind.None; } return result; }
public Options(FullPath fullPath) { Path = fullPath.RelativePath; Url = fullPath.Root.Url; ThumbnailsUrl = fullPath.Root.TmbUrl; }
public FileWithSections(IFileSystem fileSystem, FullPath filename) { _fileSystem = fileSystem; _filename = filename; _fileLines = new Lazy<IList<string>>(ReadFileLines); _hash = new Lazy<string>(ComputeHash); _sections = new Lazy<Dictionary<string, List<string>>>(ReadFile); }
public IProject GetProjectFromRootPath(FullPath projectRootPath) { var name = projectRootPath; lock (_lock) { return _knownProjectRootDirectories.Get(name); } }
public void LoadProcesses() { _processes.Clear(); List<ChromiumProcess> chromes = new List<ChromiumProcess>(); HashSet<int> chromePids = new HashSet<int>(); foreach (Process p in Process.GetProcesses()) { // System.Diagnostics.Process uses a naive implementation that is unable to deal with many // types of processes (such as those already under a debugger, or those with a high // privilege level), so use NtProcess instead. NtProcess ntproc = new NtProcess(p.Id); if (!ntproc.IsValid) continue; FullPath processPath = new FullPath(ntproc.Win32ProcessImagePath); if (processPath.StartsWith(_installationData.InstallationPath)) { chromes.Add(new ChromiumProcess(ntproc, _installationData)); chromePids.Add(p.Id); } } foreach (ChromiumProcess chrome in chromes) { // Only insert root processes at this level, child processes will be children of one of // these processes. if (!chromePids.Contains(chrome.ParentPid)) { ChromeProcessViewModel viewModel = new ChromeProcessViewModel(_root, chrome); viewModel.LoadProcesses(chromes.ToArray()); _processes.Add(viewModel); } } }
private IEnumerable<FullPath> EnumerateParents(FullPath path) { var directory = path.Parent; for (var parent = directory; parent != default(FullPath); parent = parent.Parent) { yield return parent; } }
public FileWithSections(IFileSystem fileSystem, FullPath filename) { _fileSystem = fileSystem; _filename = filename; _fileUpdateVolatileToken = new FileUpdateVolatileToken(_fileSystem, filename); _sections = new Lazy<Dictionary<string, List<string>>>(ReadFile); }
private void CreateEntries(DirectoryEntry searchResults) { if (!_enabled) return; using (new TimeElapsedLogger("Creating document tracking entries for search results")) { _searchResults.Clear(); foreach (DirectoryEntry projectRoot in searchResults.Entries) { var rootPath = new FullPath(projectRoot.Name); foreach (FileEntry fileEntry in projectRoot.Entries) { var path = rootPath.Combine(new RelativePath(fileEntry.Name)); var spans = fileEntry.Data as FilePositionsData; if (spans != null) { _searchResults[path] = spans; // If the document is open, create the tracking spans now. var document = _textDocumentTable.GetOpenDocument(path); if (document != null) { var entry = new DocumentChangeTrackingEntry(spans); _trackingEntries[path] = entry; entry.CreateTrackingSpans(document.TextBuffer); } } } } } }
public IProject GetProject(FullPath filename) { return _providers .Select(t => t.GetProjectFromAnyPath(filename)) .Where(project => project != null) .OrderByDescending(p => p.RootPath.Value.Length) .FirstOrDefault(); }
public Project(IConfigurationSectionProvider configurationSectionProvider, FullPath rootPath) { _rootPath = rootPath; _configurationToken = configurationSectionProvider.WhenUpdated(); _directoryFilter = new DirectoryFilter(configurationSectionProvider); _fileFilter = new FileFilter(configurationSectionProvider); _searchableFilesFilter = new SearchableFilesFilter(configurationSectionProvider); }
public bool ApplyCodingStyle(string filename) { var path = new FullPath(filename); var root = _chromiumDiscoveryProvider.GetEnlistmentRootFromFilename(path, x => x); if (root == default(FullPath)) return false; return _applyCodingStyleResults.GetOrAdd(filename, (key) => ApplyCodingStyleWorker(root, key)); }
public FullPath GetEnlistmentRoot(FullPath filename) { var directory = filename.Parent; if (!_fileSystem.DirectoryExists(directory)) return default(FullPath); return EnumerateParents(filename) .FirstOrDefault(x => IsChromiumSourceDirectory(x, _chromiumEnlistmentFilePatterns)); }
public static bool IsChromiumSourceDirectory(FullPath path, IPathPatternsFile chromiumEnlistmentPatterns) { // We need to ensure that all pattern lines are covered by at least one file/directory of |path|. IList<string> directories; IList<string> files; NativeFile.GetDirectoryEntries(path.Value, out directories, out files); return chromiumEnlistmentPatterns.GetPathMatcherLines() .All(item => MatchFileOrDirectory(item, directories, files)); }
public PhpSourceFile(FullPath root, FullPath fullPath) { root.EnsureNonEmpty("root"); fullPath.EnsureNonEmpty("fullPath"); this.fullPath = fullPath; this.relativePath = RelativePath.Empty; this.root = root; }
public static DateTime GetFileLastWriteTimeUtc(this IFileSystem fileSystem, FullPath path) { var fileInfo = fileSystem.GetFileInfoSnapshot(path); if (!fileInfo.Exists) { throw new IOException(string.Format("File \"{0}\" does not exist", path.Value)); } if (!fileInfo.IsFile) { throw new IOException(string.Format("File system entry \"{0}\" is not a file", path.Value)); } return fileInfo.LastWriteTimeUtc; }
public FileContents ReadFileContents(FullPath path) { try { var fileInfo = _fileSystem.GetFileInfoSnapshot(path); return ReadFileContentsWorker(fileInfo); } catch (Exception e) { Logger.LogWarning(e, "Error reading content of text file \"{0}\", skipping file.", path); return BinaryFileContents.Empty; } }
private Project CreateProject(FullPath rootPath) { var configurationProvider = _configurationSectionProvider; var section1 = ConfigurationSectionContents.Create(configurationProvider, ConfigurationSectionNames.SourceExplorerIgnoreObsolete); var section2 = ConfigurationSectionContents.Create(configurationProvider, ConfigurationSectionNames.SearchableFilesIgnore); var section3 = ConfigurationSectionContents.Create(configurationProvider, ConfigurationSectionNames.SearchableFilesInclude); var fileFilter = new FileFilter(section1); var directoryFilter = new DirectoryFilter(section1); var searchableFilesFilter = new SearchableFilesFilter(section2, section3); var hash = MD5Hash.CreateHash(section1.Contents.Concat(section2.Contents).Concat(section3.Contents)); return new Project(rootPath, fileFilter, directoryFilter, searchableFilesFilter, hash); }
public Project( FullPath rootPath, IFileFilter fileFilter, IDirectoryFilter directoryFilter, ISearchableFilesFilter searchableFilesFilter, string hash) { _rootPath = rootPath; _directoryFilter = directoryFilter; _fileFilter = fileFilter; _searchableFilesFilter = searchableFilesFilter; _hash = hash; }
private bool ApplyCodingStyleWorker(FullPath root, string filename) { var relativePath = filename.Substring(root.Value.Length); if (relativePath.Length == 0) return false; if (relativePath[0] == Path.DirectorySeparatorChar) relativePath = relativePath.Substring(1); if (relativePath.Length == 0) return false; return !_chromiumCodingStyleFilePatterns.AnyPathMatcher.MatchFileName(new RelativePath(relativePath), SystemPathComparer.Instance); }
public void TestPaths() { FullPath root; FullPath full; RelativePath rel; string str1, str2; string[,] cases = { // root: // full: // full canonical: // relative canonical: { @"C:\a/b/c/", @"D:\a/b/", @"D:\a\b\", @"D:\a\b\" }, { @"C:\a\b\c", @"C:\a\b\c", @"C:\a\b\c", @"" }, { @"C:\a\b\c", @"C:\a\b\c\", @"C:\a\b\c\", @"" }, { @"C:\a\b\c\", @"C:\a\b\c", @"C:\a\b\c", @"" }, { @"C:\a\b\c\", @"C:\a\b\c\", @"C:\a\b\c\", @"" }, { @"C:\a\b\c", @"C:\a\b", @"C:\a\b", @".." }, { @"C:\a\b\c\", @"C:\a\b", @"C:\a\b", @".." }, { @"C:\a\b\c", @"C:\", @"C:\", @"..\..\.." }, { @"C:\a\b\c\", @"C:\", @"C:\", @"..\..\.." }, { @"C:\a\b\c\", @"C:\a\b\x\y\z", @"C:\a\b\x\y\z", @"..\x\y\z" }, { @"C:\a\b\cd\", @"C:\a\b\c", @"C:\a\b\c", @"..\c" }, { @"C:\a\b\cd", @"C:\a\b\c", @"C:\a\b\c", @"..\c" }, { @"C:\a\b\cd\", @"C:\a\b\c\d", @"C:\a\b\c\d", @"..\c\d" }, { @"C:\a\b\cd", @"C:\a\b\c\d", @"C:\a\b\c\d", @"..\c\d" }, }; for (int i = 0; i < cases.GetLength(0); i++) { root = new FullPath(cases[i, 0]); full = new FullPath(cases[i, 1]); rel = new RelativePath(root, full); Assert.AreEqual(full.ToString(), cases[i, 2]); Assert.AreEqual(rel.ToString(), cases[i, 3]); str1 = full; if (str1[str1.Length - 1] == '\\') str1 = str1.Substring(0, str1.Length - 1); str2 = rel.ToFullPath(root); if (str2[str2.Length - 1] == '\\') str2 = str2.Substring(0, str2.Length - 1); Assert.AreEqual(str1, str2); Assert.AreEqual(RelativePath.ParseCanonical(cases[i, 3]).ToString(), cases[i, 3]); } }
public static InstallationData Create(NtProcess proc) { InstallationEnumerator enumerator = new InstallationEnumerator(); foreach (InstallationData data in enumerator) { FullPath fullPath = new FullPath(proc.Win32ProcessImagePath); if (fullPath.StartsWith(data.InstallationPath)) return data; } return new InstallationData( proc.Win32ProcessImagePath, InstallationLevel.Developer, 0, "Developer Chrome", String.Empty); }
private void TextDocumentOnFileActionOccurred(object sender, TextDocumentFileActionEventArgs args) { if (args.FileActionType.HasFlag(FileActionTypes.DocumentRenamed)) { var document = (ITextDocument)sender; if (FullPath.IsValid(args.FilePath)) { var newPath = new FullPath(args.FilePath); _openDocuments[newPath] = document; } if (FullPath.IsValid(document.FilePath)) { var oldPath = new FullPath(document.FilePath); _openDocuments.Remove(oldPath); } } }
public Span? TranslateSpan(string filePath, Span? span) { if (!_enabled) return span; if (span == null) return null; var path = new FullPath(filePath); var entry = _trackingEntries.GetValue(path); if (entry == null) return span; return entry.TranslateSpan(span.Value); }
private IProject GetProjectWorker(FullPath filepath) { var directory = filepath.Parent; if (_fileSystem.DirectoryExists(directory)) { var project = filepath .EnumerateParents() .Select(CreateProject) .FirstOrDefault(x => x != null); if (project != null) { _knownProjectRootDirectories.Add(project.RootPath, project); return project; } } // No one in the parent chain is a Chromium directory. filepath.EnumerateParents().ForAll(x => _knownNonProjectDirectories.Add(x, null)); return null; }
public InstallationData(string exePath, InstallationLevel level, int iconIndex, string name, string version) { string location = Path.GetDirectoryName(exePath); Distribution = DistributionType.Canary; Architecture = ProcessUtility.GetMachineType(exePath); Level = level; InstallationPath = new FullPath(location); if (InstallationPath.HasComponent("Chrome SxS")) Distribution = DistributionType.Canary; else if (InstallationPath.HasComponent("Chrome")) Distribution = DistributionType.Chrome; else Distribution = DistributionType.Chromium; IconIndex = iconIndex; Name = name; Version = version; }
/// <summary> /// Gets the name of the directory. /// </summary> /// <returns>The name of the directory.</returns> public string GetDirectoryName() { var index = FullPath.IndexOfReverse(DirectorySeparatorChar); return(index >= 0 ? FullPath.Substring(index + 1) : ""); }
public void UnregisterFile(FullPath path) { Logger.LogInfo("Unregister path \"{0}\"", path); _pendingFileRegistrations.Enqueue(FileRegistrationKind.Unregister, path); _taskQueue.Enqueue(FlushFileRegistrationQueueTaskId, FlushFileRegistrationQueueTask); }
public FileRegistrationEntry(FullPath path, FileRegistrationKind kind) { _path = path; _kind = kind; }
public async Task <JsonResult> UploadAsync(FullPath path, IEnumerable <IFormFile> files, bool?overwrite, IEnumerable <FullPath> uploadPaths, IEnumerable <string> renames, string suffix) { var response = new AddResponseModel(); if (path.RootVolume.MaxUploadSize.HasValue) { foreach (var file in files) { if (file.Length > path.RootVolume.MaxUploadSize.Value) { return(Error.MaxUploadFileSize()); } } } foreach (string rename in renames) { var fileInfo = new FileInfo(Path.Combine(path.Directory.FullName, rename)); string destination = Path.Combine(path.Directory.FullName, $"{Path.GetFileNameWithoutExtension(rename)}{suffix}{Path.GetExtension(rename)}"); fileInfo.MoveTo(destination); response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(destination), path.RootVolume)); } foreach (var uploadPath in uploadPaths) { var directory = uploadPath.Directory; while (directory.FullName != path.RootVolume.RootDirectory) { response.Added.Add(await BaseModel.CreateAsync(new FileSystemDirectory(directory.FullName), path.RootVolume)); directory = directory.Parent; } } int i = 0; foreach (var file in files) { string destination = uploadPaths.Count() > i?uploadPaths.ElementAt(i).Directory.FullName : path.Directory.FullName; var fileInfo = new FileInfo(Path.Combine(destination, Path.GetFileName(file.FileName))); if (fileInfo.Exists) { if (overwrite ?? path.RootVolume.UploadOverwrite) { fileInfo.Delete(); using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Create)) { await file.CopyToAsync(fileStream); } response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(fileInfo.FullName), path.RootVolume)); } else { string newName = CreateNameForCopy(fileInfo, suffix); using (var fileStream = new FileStream(Path.Combine(fileInfo.DirectoryName, newName), FileMode.Create)) { await file.CopyToAsync(fileStream); } response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(newName), path.RootVolume)); } } else { using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Create)) { await file.CopyToAsync(fileStream); } response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(fileInfo.FullName), path.RootVolume)); } i++; } return(await Json(response)); }
public async Task <JsonResult> ExtractAsync(FullPath fullPath, bool newFolder) { var response = new AddResponseModel(); if (fullPath.IsDirectory || fullPath.File.Extension.ToLower() != ".zip") { throw new NotSupportedException("Only .zip files are currently supported."); } string rootPath = fullPath.File.Directory.FullName; if (newFolder) { rootPath = Path.Combine(rootPath, Path.GetFileNameWithoutExtension(fullPath.File.Name)); var rootDir = new FileSystemDirectory(rootPath); if (!await rootDir.ExistsAsync) { await rootDir.CreateAsync(); } response.Added.Add(await BaseModel.CreateAsync(rootDir, fullPath.RootVolume)); } using (var archive = ZipFile.OpenRead(fullPath.File.FullName)) { string separator = Path.DirectorySeparatorChar.ToString(); foreach (ZipArchiveEntry entry in archive.Entries) { try { //Replce zip entry path separator by system path separator string file = Path.Combine(rootPath, entry.FullName) .Replace("/", separator).Replace("\\", separator); if (file.EndsWith(separator)) //directory { var dir = new FileSystemDirectory(file); if (!await dir.ExistsAsync) { await dir.CreateAsync(); } if (!newFolder) { response.Added.Add(await BaseModel.CreateAsync(dir, fullPath.RootVolume)); } } else { entry.ExtractToFile(file, true); if (!newFolder) { response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(file), fullPath.RootVolume)); } } } catch //(Exception ex) { //throw new Exception(entry.FullName, ex); } } } return(await Json(response)); }
public IProject GetProjectFromRootPath(FullPath projectRootPath) { return(_providers .Select(t => t.GetProjectFromRootPath(projectRootPath)) .FirstOrDefault(project => project != null)); }
/// <summary> /// 使用OsuBeatmap初始化Beatmap对象 /// </summary> /// <param name="beatmap"></param> /// <param name="getStars"></param> public Beatmap(OsuBeatmap beatmap, bool getStars = true) { var info = new OsuInfo(); Title = beatmap.Title; TitleUnicode = beatmap.TitleUnicode; Artist = beatmap.Artist; ArtistUnicode = beatmap.ArtistUnicode; Creator = beatmap.Creator; Difficulty = beatmap.Difficulty; Version = Difficulty; FileName = beatmap.FileName; FullPath = Path.Combine(info.BeatmapDirectory, beatmap.FolderName, beatmap.FileName); DownloadLink = $"http://osu.ppy.sh/b/{beatmap.BeatmapId}"; Source = beatmap.Source; Tags = beatmap.Tags; Maker = ""; Md5 = new MD5String(beatmap.Md5); FullAudioFileName = Path.Combine(info.BeatmapDirectory, beatmap.FolderName, beatmap.AudioFileName); FullVideoFileName = ""; OverallDifficulty = beatmap.OverallDifficulty; HpDrain = beatmap.HpDrain; ApproachRate = beatmap.ApproachRate; CircleSize = beatmap.CircleSize; BeatmapSetId = beatmap.BeatmapSetId; AudioFileName = beatmap.AudioFileName; Mode = beatmap.Mode; if (getStars) { double.TryParse(beatmap.Stars.ToString(CultureInfo.InvariantCulture), out var stars); Stars = stars; } else { Stars = 0; } if (FullPath == "" || !File.Exists(FullPath)) { return; } var alllines = File.ReadAllLines(FullPath); if (!alllines[0].Contains("osu file format")) { NotValid = true; throw new InvalidBeatmapFileException($"文件{FullPath}不是谱面文件。"); } StringBuilder b = new StringBuilder(); foreach (var c in alllines[0]) { if (char.IsDigit(c)) { b.Append(c); } } BeatmapVersion = int.Parse(b.ToString()); foreach (var line in alllines) { var temparr = line.Split(':'); if (temparr[0].StartsWith("0,0,\"")) { if (string.IsNullOrEmpty(BackgroundFileName)) { BackgroundFileName = temparr[0].Split(',')[2].Replace("\"", "").Trim(); } FullBackgroundFileName = Path.Combine(BeatmapFolder, BackgroundFileName); continue; } if (temparr[0].StartsWith("Video,")) { VideoFileName = temparr[0].Split(',')[2].Replace("\"", "").Trim(); FullVideoFileName = Path.Combine(BeatmapFolder, FullVideoFileName); HasVideo = !string.IsNullOrEmpty(VideoFileName); continue; } FullVideoFileName = FullPath.Replace(FileName, VideoFileName); if (line.Contains("TimingPoints")) { break; } } BeatmapId = beatmap.BeatmapId; getAddtionalInfo(alllines); }
/// <summary> /// Compares this to other.</summary> public int CompareTo(CustomFileSystemResourceFolder other) { return(FullPath.CompareTo(other.FullPath)); }
/// <summary> /// Obtains hash code</summary> /// <returns>Hash code</returns> public override int GetHashCode() { return(FullPath.GetHashCode()); }
/// <summary> </summary> public Options(FullPath fullPath) { path = fullPath.RelativePath; url = fullPath.Root.Url; tmbUrl = fullPath.Root.TmbUrl; }
public void MoveTo(String destDirName) { if (destDirName == null) { throw new ArgumentNullException("destDirName"); } if (destDirName.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName"); } Contract.EndContractBlock(); #if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, Directory.GetDemandDir(FullPath, true)); sourceState.EnsureState(); #elif !FEATURE_CORECLR new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandDir, false, false).Demand(); #endif String fullDestDirName = Path.GetFullPathInternal(destDirName); String demandPath; if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar)) { fullDestDirName = fullDestDirName + Path.DirectorySeparatorChar; } demandPath = fullDestDirName + '.'; // Demand read & write permission to destination. The reason is // we hand back a DirectoryInfo to the destination that would allow // you to read a directory listing from that directory. Sure, you // had the ability to read the file contents in the old location, // but you technically also need read permissions to the new // location as well, and write is not a true superset of read. #if FEATURE_CORECLR && !FEATURE_LEGACYNETCFIOSECURITY FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, demandPath); destState.EnsureState(); #elif !FEATURE_CORECLR new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandPath).Demand(); #endif String fullSourcePath; if (FullPath.EndsWith(Path.DirectorySeparatorChar)) { fullSourcePath = FullPath; } else { fullSourcePath = FullPath + Path.DirectorySeparatorChar; } if (String.Compare(fullSourcePath, fullDestDirName, StringComparison.OrdinalIgnoreCase) == 0) { throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent")); } String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0) { throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot")); } if (!Win32Native.MoveFile(FullPath, destDirName)) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code { hr = Win32Native.ERROR_PATH_NOT_FOUND; __Error.WinIOError(hr, DisplayPath); } if (hr == Win32Native.ERROR_ACCESS_DENIED) // We did this for Win9x. We can't change it for backcomp. { throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", DisplayPath)); } __Error.WinIOError(hr, String.Empty); } FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); demandDir = new String[] { Directory.GetDemandDir(FullPath, true) }; // Flush any cached information about the directory. _dataInitialised = -1; }
/// <summary> /// Initializes a new instance of the <see cref="NormalizedPath" /> class. /// </summary> /// <param name="providerAndPath">The provider and path as a Tuple so it can /// be passed from both of the other constructors.</param> /// <param name="fullySpecified">If set to <c>true</c> indicates that this constructor was /// called from one where the provider and path were fully specified (as opposed to being inferred).</param> /// <param name="pathKind">Specifies whether the path is relative, absolute, or indeterminate.</param> private NormalizedPath(Tuple <Uri, string> providerAndPath, bool fullySpecified, PathKind pathKind) { if (providerAndPath.Item2 == null) { throw new ArgumentNullException(); } if (string.IsNullOrWhiteSpace(providerAndPath.Item2)) { throw new ArgumentException("Path cannot be empty"); } // Leave spaces since they're valid path chars FullPath = providerAndPath.Item2.Replace('\\', '/').Trim('\r', '\n', '\t'); // Remove relative part of a path, but only if it's not the only part if (FullPath.StartsWith("./", StringComparison.Ordinal) && FullPath.Length > 2) { FullPath = FullPath.Substring(2); } // Remove trailing slashes (as long as this isn't just a slash) if (FullPath.Length > 1) { FullPath = FullPath.TrimEnd('/'); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && FullPath.EndsWith(":", StringComparison.OrdinalIgnoreCase)) { FullPath = string.Concat(FullPath, "/"); } // Absolute path? switch (pathKind) { case PathKind.RelativeOrAbsolute: IsAbsolute = System.IO.Path.IsPathRooted(FullPath); break; case PathKind.Absolute: IsAbsolute = true; break; case PathKind.Relative: IsAbsolute = false; break; } // Set provider (but only if absolute) if (IsRelative && providerAndPath.Item1 != null) { throw new ArgumentException("Can not specify provider for relative paths"); } if (providerAndPath.Item1 == null && IsAbsolute && !fullySpecified) { FileProvider = DefaultFileProvider; } else if (providerAndPath.Item1?.IsAbsoluteUri == false) { throw new ArgumentException("The provider URI must always be absolute"); } else { FileProvider = providerAndPath.Item1; } // Extract path segments. Segments = FullPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); }
/// <summary> /// Returns a <see cref="string" /> that represents this path. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { if (IsRelative || FileProvider == null) { return(FullPath); } string rightPart = GetRightPart(FileProvider); if (string.IsNullOrEmpty(rightPart) || rightPart == "/") { // Remove the proceeding slash from FullPath if the provider already has one return(FileProvider + (rightPart == "/" && FullPath.StartsWith("/") ? FullPath.Substring(1) : FullPath)); } return(FileProvider + FileProviderDelimiter + FullPath); }
public override int GetHashCode() { return(FullPath != null ? FullPath.GetHashCode() : 0); }
public override int GetHashCode() => FullPath.GetHashCode() ^ Visible.GetHashCode();
private List <FileFullPath> RemoveDuplicateFiles(List <FileFullPath> filesToZip, FullPath baseDir) { ZipMetadata metadata = new ZipMetadata(); List <FileFullPath> list = new List <FileFullPath>(); while (filesToZip.Count > 0) { FileFullPath current = filesToZip[filesToZip.Count - 1]; var currentDebase = current.ToFullPath().DebasePath(baseDir); filesToZip.RemoveAt(filesToZip.Count - 1); ZipMetadataItem metaItem = new ZipMetadataItem { FileName = currentDebase }; metaItem.DestinationFiles.Add(currentDebase); metadata.Items.Add(metaItem); list.Add(current); byte[] firstHash = CalculateHash(current.ToString()); FileInfo currentInfo = new FileInfo(current.ToString()); for (int i = filesToZip.Count - 1; i >= 0; i--) { FileFullPath tmp = filesToZip[i]; if (tmp.FileName != current.FileName) { continue; } FileInfo tmpInfo = new FileInfo(tmp.ToString()); if (tmpInfo.Length != currentInfo.Length) { continue; } byte[] secondHash = CalculateHash(tmp.ToString()); if (!HashEqual(firstHash, secondHash)) { continue; } metaItem.DestinationFiles.Add(tmp.ToFullPath().DebasePath(baseDir)); filesToZip.RemoveAt(i); } } string metadataFile = Path.Combine(baseDir.ToString(), MetadataFileName); File.WriteAllText(metadataFile, JsonConvert.SerializeObject(metadata)); list.Add(new FileFullPath(metadataFile)); return(list); }
private static void TargetNuGet(ITaskContext context, string nugetId) { FullPath packagesDir = new FullPath(context.Properties.Get(BuildProps.ProductRootDir, ".")); packagesDir = packagesDir.CombineWith(context.Properties.Get <string>(BuildProps.BuildDir)); string sourceNuspecFile = string.Format( CultureInfo.InvariantCulture, @"{0}\{0}.nuspec", nugetId); FileFullPath destNuspecFile = packagesDir.AddFileName("{0}.nuspec", nugetId); context.WriteInfo("Preparing the {0} file", destNuspecFile); ExpandPropertiesTask task = new ExpandPropertiesTask( sourceNuspecFile, destNuspecFile.ToString(), Encoding.UTF8, Encoding.UTF8); task.AddPropertyToExpand("version", context.Properties.Get <Version>(BuildProps.BuildVersion).ToString()); task.Execute(context); // package it context.WriteInfo("Creating a NuGet package file"); RunProgramTask progTask = new RunProgramTask(@"lib\NuGet\NuGet.exe"); progTask.SetWorkingDir(destNuspecFile.Directory.ToString()); progTask .AddArgument("pack") .AddArgument(destNuspecFile.FileName) .AddArgument("-Verbose") .Execute(context); string nupkgFileName = string.Format( CultureInfo.InvariantCulture, "{0}.{1}.nupkg", nugetId, context.Properties.Get <Version>(BuildProps.BuildVersion)); context.WriteInfo("NuGet package file {0} created", nupkgFileName); string apiKeyFileName = "NuGet API key.txt"; if (!File.Exists(apiKeyFileName)) { context.WriteInfo("'NuGet API key.txt' does not exist, cannot publish the package."); return; } string apiKey = File.ReadAllText(apiKeyFileName); // publish the package file context.WriteInfo("Pushing the NuGet package to the repository"); progTask = new RunProgramTask(@"lib\NuGet\NuGet.exe"); progTask.SetWorkingDir(destNuspecFile.Directory.ToString()); progTask .AddArgument("push") .AddArgument(nupkgFileName) .AddArgument(apiKey) .AddArgument("-Source") .AddArgument("http://packages.nuget.org/v1/") .Execute(context); }
// Force a file to be resolved to a specific path regardless of conflicts. internal void ForceFile(Utf8GamePath path, FullPath fullPath) => _cache !.ResolvedFiles[path] = new ModPath(Mod.ForcedFiles, fullPath);
static void Main(string[] args) { int zadach; Console.WriteLine("\nВведите номер задачи:\n"); zadach = Convert.ToInt32(Console.ReadLine()); if (zadach == 1) { char[] s; Console.Write("Введите строку: "); s = Console.ReadLine().ToCharArray(); int k = 1; for (int i = 0; i < s.Length; i++) { if ((s[i] == ' ') && (s[i - 1] != ' ')) { k++; } } Console.Write(k); } if (zadach == 2) { string s; Console.Write("Введите строку: "); s = Console.ReadLine(); var word = from min in s.Split(' ') orderby min.Length select min; string minword = word.First(); Console.Write(minword.Length); } if (zadach == 3) { char[] s; char c; Console.Write("Введите строку: "); s = Console.ReadLine().ToArray(); c = s[0]; for (int i = 1; i < s.Length; i++) { if (s[i] == c) { s[i] = '.'; } } Console.Write(s); } if (zadach == 4) { string s; char[] glas = { 'А', 'а', 'Е', 'е', 'Ё', 'ё', 'И', 'и', 'О', 'о', 'У', 'у', 'ы', 'Э', 'э', 'Ю', 'ю', 'Я', 'я' }; Console.Write("Введите строку: "); s = Console.ReadLine(); int k = 0; for (int i = 0; i < s.Length; i++) { for (int j = 0; j < glas.Length; j++) { if (s[i] == glas[j]) { k++; } } } Console.Write(k); } if (zadach == 5) { string FullPath; Console.Write("Введите полный путь к файлу: "); FullPath = Console.ReadLine(); Console.Write(Path.GetFileNameWithoutExtension(FullPath)); Console.ReadKey(); } if (zadach == 6) { string FullPath; Console.Write("Введите полный путь к файлу: "); FullPath = Console.ReadLine(); if ((char)(FullPath.Split('\\').Length) > 2) { Console.WriteLine(FullPath.Split('\\')[FullPath.Split('\\').Length - 2]); } else { Console.WriteLine("\\ "); } } if (zadach == 7) { string s; Console.Write("Введите строку: "); s = Console.ReadLine(); for (int i = 0; i < s.Length; i++) { if (i % 2 != 0) { Console.Write(s[i]); } } for (int i = s.Length - 1; i >= 0; i--) { if (i % 2 == 0) { Console.Write(s[i]); } } } }
public SlimFileInfo(FullPath path, WIN32_FILE_ATTRIBUTE_DATA data, int win32Error) { _path = path; _data = data; _win32Error = win32Error; }
public async Task <JsonResult> UploadAsync(FullPath path, IEnumerable <IFormFile> files) { int fileCount = files.Count(); var response = new AddResponseModel(); if (path.RootVolume.MaxUploadSize.HasValue) { for (int i = 0; i < fileCount; i++) { IFormFile file = files.ElementAt(i); if (file.Length > path.RootVolume.MaxUploadSize.Value) { return(Error.MaxUploadFileSize()); } } } foreach (var file in files) { var p = new FileInfo(Path.Combine(path.Directory.FullName, Path.GetFileName(file.FileName))); if (p.Exists) { if (path.RootVolume.UploadOverwrite) { //if file already exist we rename the current file, //and if upload is succesfully delete temp file, in otherwise we restore old file string tmpPath = p.FullName + Guid.NewGuid(); bool uploaded = false; try { using (var fileStream = new FileStream(tmpPath, FileMode.Create)) { await file.CopyToAsync(fileStream); } uploaded = true; } catch { } finally { if (uploaded) { File.Delete(p.FullName); File.Move(tmpPath, p.FullName); } else { File.Delete(tmpPath); } } } else { using (var fileStream = new FileStream(Path.Combine(p.DirectoryName, Utils.GetDuplicatedName(p)), FileMode.Create)) { await file.CopyToAsync(fileStream); } } } else { using (var fileStream = new FileStream(p.FullName, FileMode.Create)) { await file.CopyToAsync(fileStream); } } response.Added.Add((FileModel)await BaseModel.Create(this, new FileSystemFile(p.FullName), path.RootVolume)); } return(await Json(response)); }
void recursivePathDive(Library lib, string dirPath) { string[] Directories = Directory.GetDirectories(dirPath, @"*", SearchOption.TopDirectoryOnly); string[] Files = Directory.GetFiles(dirPath, @"*", SearchOption.TopDirectoryOnly); foreach (string FullPath in Files) { string SubPath = FullPath.Substring(lib.Path.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); Alexandria.Models.File tmp = MusicContext.Files.Where(dr => dr.Library.Equals(lib) && dr.Path == SubPath).FirstOrDefault(); if (tmp == null) { // do we want to track this file? string FileExtension = ExtensionsToMonitor.Where(dr => Path.GetFileName(FullPath).EndsWith(dr)).FirstOrDefault(); if (FileExtension == null) { ConsoleColor tmpConCol = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine($"Skip\t{lib.Path} | {SubPath}"); Console.ForegroundColor = tmpConCol; continue; } { ConsoleColor tmpConCol = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"New\t{lib.Path} | {SubPath}"); Console.ForegroundColor = tmpConCol; } // gather file data // add to db Alexandria.Models.File newFile = new Alexandria.Models.File() { Library = lib, Archival = false, FileModified = System.IO.File.GetLastWriteTimeUtc(FullPath), RecordAdded = DateTime.UtcNow, Path = SubPath, Tags = new List <TagAssociation>() }; //TagAdder tagAdderRecord = new TagAdder() { Timestamp = DateTime.UtcNow, User = systemAccount }; //TagAssociation newTagAssoc = new TagAssociation() { Tag = unTaggedTag, Added = new List<TagAdder>() }; //newTagAssoc.Added.Add(tagAdderRecord); //newFile.Tags.Add(newTagAssoc); newFile.AddTag(unTaggedTag, systemAccount); MusicContext.Files.Add(newFile); MusicContext.SaveChanges(); } else { /* * // skip file unless modified date has changed * * // do we want to track this file? * string FileExtension = ExtensionsToMonitor.Where(dr => Path.GetFileName(FullPath).EndsWith(dr)).FirstOrDefault(); * if (FileExtension == null) continue; * * DateTime FileModDate = System.IO.File.GetLastWriteTimeUtc(FullPath); * if(FileModDate > tmp.Modified) * { * Console.WriteLine($"Changed\t{lib.Path} | {SubPath}"); * } */ { ConsoleColor tmpConCol = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine($"Known\t{lib.Path} | {SubPath}"); Console.ForegroundColor = tmpConCol; } } } foreach (string Directory in Directories) { recursivePathDive(lib, Directory); } }
public async Task <JsonResult> InitAsync(FullPath path, IEnumerable <string> mimeTypes) { if (path == null) { var root = Roots.FirstOrDefault(r => r.StartDirectory != null); if (root == null) { root = Roots.First(); } if (Directory.Exists(root.StartDirectory)) { path = new FullPath(root, new FileSystemDirectory(root.StartDirectory), null); } if (path == null || path.Directory.GetReadFlag(root) == 0) { path = new FullPath(root, new FileSystemDirectory(root.RootDirectory), null); } } var response = new InitResponseModel(await BaseModel.CreateAsync(path.Directory, path.RootVolume), new Options(path)); foreach (var item in await path.Directory.GetFilesAsync(mimeTypes)) { if (!item.Attributes.HasFlag(FileAttributes.Hidden)) { response.Files.Add(await BaseModel.CreateAsync(item, path.RootVolume)); } } foreach (var item in await path.Directory.GetDirectoriesAsync()) { if (!item.Attributes.HasFlag(FileAttributes.Hidden)) { response.Files.Add(await BaseModel.CreateAsync(item, path.RootVolume)); } } foreach (var item in Roots) { response.Files.Add(await BaseModel.CreateAsync(new FileSystemDirectory(item.RootDirectory), item)); } if (path.RootVolume.RootDirectory != path.Directory.FullName) { var dirInfo = new DirectoryInfo(path.RootVolume.RootDirectory); foreach (var item in dirInfo.GetDirectories()) { var attributes = item.Attributes; if (!attributes.HasFlag(FileAttributes.Hidden)) { response.Files.Add(await BaseModel.CreateAsync(new FileSystemDirectory(item), path.RootVolume)); } } } if (path.RootVolume.MaxUploadSize.HasValue) { response.Options.UploadMaxSize = $"{path.RootVolume.MaxUploadSizeInKb.Value}K"; } return(await Json(response)); }
public IEnumerable <Utf8GamePath> ReverseResolvePath(FullPath path) => _cache?.ReverseResolvePath(path) ?? Array.Empty <Utf8GamePath>();
public int GetLevel() { return(FullPath.Split('.').Length); }
public void TestInitialize() { // Create a new root folder every time to avoid mixing state between tests. this.root = new FullPath(@".\fstest\" + Guid.NewGuid().ToString("n")); Directory.CreateDirectory(this.root.ToString()); }
public IProject GetProjectFromAnyPath(FullPath path) { return(_chromiumDiscovery.GetEnlistmentRootFromAnyPath(path, CreateProject)); }
protected override int DoExecute(ITaskContextInternal context) { if (_sourcePackagingInfos.Count == 0) { return(0); } if (string.IsNullOrEmpty(_destinationRootDir)) { _destinationRootDir = context.Properties.GetOutputDir(); } FullPath df = new FullPath(_destinationRootDir); ICopier copier = new Copier(context, _logFiles); IZipper zipper = new Zipper(context); IDirectoryFilesLister directoryFilesLister = new DirectoryFilesLister(); StandardPackageDef packageDef = new StandardPackageDef(); CopyProcessor copyProcessor = new CopyProcessor(context, copier, df, _logFiles); List <string> sourceIds = new List <string>(); foreach (var sourceToPackage in _sourcePackagingInfos) { string sourceId; if (sourceToPackage.SourceType == SourceType.Directory) { var sourceFullPath = new FullPath(sourceToPackage.SourcePath); sourceId = sourceFullPath.GetHashCode().ToString(); DirectorySource directorySource = new DirectorySource(context, directoryFilesLister, sourceId, sourceFullPath, sourceToPackage.Recursive, sourceToPackage.DirectoryFilters, _logFiles); directorySource.SetFileFilter(sourceToPackage.FileFilters); packageDef.AddFilesSource(directorySource); } else { var fileFullPath = new FileFullPath(sourceToPackage.SourcePath); sourceId = fileFullPath.GetHashCode().ToString(); SingleFileSource fileSource = new SingleFileSource(sourceId, fileFullPath); packageDef.AddFilesSource(fileSource); } copyProcessor.AddTransformation(sourceId, sourceToPackage.DestinationPath); sourceIds.Add(sourceId); } IPackageDef copiedPackageDef = copyProcessor.Process(packageDef); if (ShouldPackageBeZipped) { string zipFile = _zipFileName; if (string.IsNullOrEmpty(zipFile)) { zipFile = _zipPrefix; _addVersionAsPostFixToZipFileName = true; _versionFieldCount = 3; } if (zipFile.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) { zipFile = zipFile.Substring(0, zipFile.Length - 4); } string tmp = _addVersionAsPostFixToZipFileName ? $"{zipFile}_{context.Properties.GetBuildVersion().Version.ToString(_versionFieldCount)}.zip" : $"{zipFile}.zip"; zipFile = Path.Combine(_destinationRootDir, tmp); DoLogInfo($"Creating zip file {zipFile}"); ZipProcessor zipProcessor = new ZipProcessor(context, zipper, new FileFullPath(zipFile), df, _optimizeZip, sourceIds, _logFiles); zipProcessor.Process(copiedPackageDef); } return(0); }
public DirectoryInfo CreateSubdirectory(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) { throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); } if (Path.IsPathRooted(path)) { throw new ArgumentException(SR.Arg_Path2IsRooted, nameof(path)); } string newPath = Path.GetFullPath(Path.Combine(FullPath, path)); ReadOnlySpan <char> trimmedNewPath = Path.TrimEndingDirectorySeparator(newPath.AsSpan()); ReadOnlySpan <char> trimmedCurrentPath = Path.TrimEndingDirectorySeparator(FullPath.AsSpan()); // We want to make sure the requested directory is actually under the subdirectory. if (trimmedNewPath.StartsWith(trimmedCurrentPath, PathInternal.StringComparison) // Allow the exact same path, but prevent allowing "..\FooBar" through when the directory is "Foo" && ((trimmedNewPath.Length == trimmedCurrentPath.Length) || PathInternal.IsDirectorySeparator(newPath[trimmedCurrentPath.Length]))) { FileSystem.CreateDirectory(newPath); return(new DirectoryInfo(newPath)); } // We weren't nested throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, FullPath), nameof(path)); }
public OpenResponse(DTOBase currentWorkingDirectory, FullPath fullPath) : base(currentWorkingDirectory) { Options = new Options(fullPath); _files.Add(currentWorkingDirectory); }