public void FullPath() { // Tests from https://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx string input, expected; // GetFullPath('mydir') returns 'C:\temp\Demo\mydir' input = @"mydir"; expected = WorkingDirectory + SysPath.DirectorySeparatorChar + @"mydir"; Assert.Equal(expected, new Path(input).FullPathString); // GetFullPath('myfile.ext') returns 'C:\temp\Demo\myfile.ext' input = @"myfile.ext"; expected = WorkingDirectory + SysPath.DirectorySeparatorChar + @"myfile.ext"; Assert.Equal(expected, new Path(input).FullPathString); // GetFullPath('\mydir') returns 'C:\mydir' input = @"\mydir"; expected = SysPath.GetPathRoot(WorkingDirectory) + @"mydir"; Assert.Equal(expected, new Path(input).FullPathString); input = @"/mydir"; expected = SysPath.GetPathRoot(WorkingDirectory) + @"mydir"; Assert.Equal(expected, new Path(input).FullPathString); input = @"c:\mydir"; expected = @"c:\mydir"; Assert.Equal(expected, new Path(input).FullPathString); input = @"m:\mydir"; expected = @"m:\mydir"; Assert.Equal(expected, new Path(input).FullPathString); }
public static PathSplitResult SplitDirectoryFile(string path) { if (path == null) { return(null); } int rootLength = Path.GetPathRoot(path).Length; path = IgnoreTrailingSlashIfAny(path, rootLength); if (TryGetPivotIndex(path, rootLength, out int pivotIndex)) { return(new PathSplitResult { Directory = path.Substring(0, pivotIndex), File = path.Substring(pivotIndex + 1, path.Length - pivotIndex - 1) }); } else { return(new PathSplitResult { Directory = path.Substring(0, path.Length) }); } }
void GetRouteAndBasePath(string file, out string routePath, out string basePath) { routePath = null; basePath = null; Stack <string> subDirectories = new Stack <string>(); string directory = Path.GetDirectoryName(file); var root = Path.GetPathRoot(file); while (directory.Length > root.Length) { string subdDirectoryName = Path.GetFileName(directory); if (subdDirectoryName.ToLowerInvariant().Equals("routes")) { routePath = Path.Combine(directory, subDirectories.Pop()); basePath = Path.GetDirectoryName(Path.GetDirectoryName(routePath)); return; } if (subdDirectoryName.ToLowerInvariant().Equals("trains")) { basePath = Path.GetDirectoryName(directory); return; } if (subdDirectoryName.ToLowerInvariant().Equals("trains")) { basePath = Path.GetDirectoryName(directory); } if (subdDirectoryName.ToLowerInvariant().Equals("sound")) { basePath = Path.GetDirectoryName(directory); } subDirectories.Push(Path.GetFileName(directory)); directory = Path.GetDirectoryName(directory); } }
private static void GetRouteAndBasePath(string file, out string routePath, out string basePath) { routePath = null; basePath = null; Stack <string> subDirectories = new Stack <string>(); string directory = Path.GetDirectoryName(file); string root = Path.GetPathRoot(file); while (directory.Length > root.Length) { string subdDirectoryName = Path.GetFileName(directory); if (subdDirectoryName.Equals("routes", System.StringComparison.OrdinalIgnoreCase)) { routePath = Path.Combine(directory, subDirectories.Pop()); basePath = Path.GetDirectoryName(Path.GetDirectoryName(routePath)); return; } if (subdDirectoryName.Equals("trains", System.StringComparison.OrdinalIgnoreCase)) { basePath = Path.GetDirectoryName(directory); return; } if (subdDirectoryName.Equals("trains", System.StringComparison.OrdinalIgnoreCase)) { basePath = Path.GetDirectoryName(directory); } if (subdDirectoryName.Equals("sound", System.StringComparison.OrdinalIgnoreCase)) { basePath = Path.GetDirectoryName(directory); } subDirectories.Push(Path.GetFileName(directory)); directory = Path.GetDirectoryName(directory); } }
private void _initCacheDirectory(Directory cacheDirectory) { if (cacheDirectory != null) { // save it off _cacheDirectory = cacheDirectory; } else { var cachePath = Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), "AzureDirectory"); var azureDir = new DirectoryInfo(cachePath); if (!azureDir.Exists) { azureDir.Create(); } var catalogPath = Path.Combine(cachePath, _containerName); var catalogDir = new DirectoryInfo(catalogPath); if (!catalogDir.Exists) { catalogDir.Create(); } _cacheDirectory = FSDirectory.Open(new DirectoryInfo(catalogPath)); } CreateContainer(); }
private static int Handle(string[] inputs, FileInfo schema) { string schemaText = System.IO.File.ReadAllText(schema.FullName); var jSchema = Newtonsoft.Json.Schema.JSchema.Parse(schemaText); string cwd = System.IO.Directory.GetCurrentDirectory(); bool failed = false; foreach (string pattern in inputs) { IEnumerable <string> paths; if (Path.IsPathRooted(pattern)) { var root = Path.GetPathRoot(pattern); if (root == null) { throw new ArgumentException( $"Root could not be retrieved from rooted pattern: {pattern}"); } var relPattern = Path.GetRelativePath(root, pattern); paths = GlobExpressions.Glob.Files(root, relPattern) .Select((path) => Path.Join(root, relPattern)); } else { paths = GlobExpressions.Glob.Files(cwd, pattern) .Select((path) => Path.Join(cwd, path)); } foreach (string path in paths) { string text = System.IO.File.ReadAllText(path); var jObject = Newtonsoft.Json.Linq.JObject.Parse(text); bool valid = jObject.IsValid(jSchema, out IList <string> messages); if (!valid) { Console.Error.WriteLine($"FAIL: {path}"); foreach (string message in messages) { Console.Error.WriteLine(message); } failed = true; } else { Console.WriteLine($"OK: {path}"); } } } return((failed) ? 1 : 0); }
/// <summary> /// Determines if a path is a full, absolute path by checking against a set of /// rules to weed out any non-full paths. /// </summary> /// <param name="path">The path to test.</param> /// <returns>True, if it is a full path.</returns> /// <remarks>Has specific checking to look for both Windows and Unix-like paths.</remarks> public static bool IsFullPath(string path) { // if the string is empty, has invalid characters, or isn't rooted, it's not a full path. if (string.IsNullOrWhiteSpace(path) || path.IndexOfAny(SPath.GetInvalidPathChars()) != -1 || !SPath.IsPathRooted(path)) { return(false); } // grab the root string pathRoot = SPath.GetPathRoot(path); // If the root is less than 2 characters, it can't be: // - A windows drive (e.g.: "C:\") // - A UNC path (e.g.: "\\name") // If it *is* one character, but that character is a forward slash, // it could be a Unix-like path. if (pathRoot.Length <= 2 && pathRoot.StartsWith("/") == false) { return(false); } // A UNC path without a share name (e.g "\\server") is invalid, and not a full path. return(!(pathRoot == path && pathRoot.StartsWith("\\\\") && pathRoot.IndexOf('\\', 2) == -1)); }
/// <summary> /// Matches all the files defined by the patterns, includes and excludes. /// If any of the patterns is given as a relative directory, /// current working directory is prepended. /// </summary> /// <param name="cwd">current working directory</param> /// <param name="patterns">GLOB patterns to match files for inspection</param> /// <param name="excludes">GLOB patterns to exclude files matching patterns</param> /// <returns>Paths of the matched files</returns> public static IEnumerable <string> MatchFiles( string cwd, List <string> patterns, List <string> excludes) { //// // Pre-condition(s) //// if (cwd.Length == 0) { throw new ArgumentException("Expected a non-empty cwd"); } if (!Path.IsPathRooted(cwd)) { throw new ArgumentException("Expected cwd to be rooted"); } //// // Implementation //// if (patterns.Count == 0) { yield break; } var globExcludes = excludes.Select( (pattern) => { string rootedPattern = (Path.IsPathRooted(pattern)) ? pattern : Path.Join(cwd, pattern); return(new GlobExpressions.Glob(rootedPattern)); }).ToList(); foreach (var pattern in patterns) { IEnumerable <string>?files; if (Path.IsPathRooted(pattern)) { var root = Path.GetPathRoot(pattern); if (root == null) { throw new ArgumentException( $"Root could not be retrieved from rooted pattern: {pattern}"); } var relPattern = Path.GetRelativePath(root, pattern); files = GlobExpressions.Glob.Files(root, relPattern) .Select((path) => Path.Join(root, path)); } else { files = GlobExpressions.Glob.Files(cwd, pattern); } List <string> accepted = files .Where((path) => { string rootedPath = (Path.IsPathRooted(path)) ? path : Path.Join(cwd, path); return(globExcludes.TrueForAll((glob) => !glob.IsMatch(rootedPath))); }) .ToList(); accepted.Sort(StringComparer.InvariantCulture); foreach (string path in accepted) { yield return(path); } } }
private static bool ValidateInputs() { // needs to get refactored with EnumerateFiles function and search pattern like *.xml - looks not right string cwd = System.IO.Directory.GetCurrentDirectory(); var valid = xmlInputs.Count() > 0; foreach (string pattern in xmlInputs) { IEnumerable <string> paths; if (Path.IsPathRooted(pattern)) { var root = Path.GetPathRoot(pattern); if (root == null) { throw new ArgumentException( $"Root could not be retrieved from rooted pattern: {pattern}"); } var relPattern = Path.GetRelativePath(root, pattern); paths = GlobExpressions.Glob.Files(root, relPattern) .Select((path) => Path.Join(root, relPattern)); } else { paths = GlobExpressions.Glob.Files(cwd, pattern) .Select((path) => Path.Join(cwd, path)); } foreach (string path in paths) { XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = xmlSchemaSet; var messages = new List <string>(); settings.ValidationEventHandler += (object sender, ValidationEventArgs e) => { messages.Add(e.Message); }; XmlReader reader = XmlReader.Create(path, settings); while (reader.Read()) { // Invoke callbacks } ; if (messages.Count > 0) { Console.Error.WriteLine($"FAIL: {path}"); foreach (string message in messages) { Console.Error.WriteLine(message); } valid = valid & false; } else { Console.WriteLine($"OK: {path}"); valid = valid & true; } } } return(valid); }
private async Task LoadAsync(string fileName, bool recreateModelAndMaterialFiles) { Debug.Assert(_tempDirectoryHelper == null); Debug.Assert(_monoGameContent == null); Debug.Assert(ModelNode == null); Debug.Assert(Model == null); Debug.Assert(_assimpScene == null); Debug.Assert(State == ModelDocumentState.Loading); string extension = Path.GetExtension(fileName); IsXnb = string.Compare(extension, ".XNB", StringComparison.OrdinalIgnoreCase) == 0; // ----- Build XNB string directoryName; try { if (IsXnb) { // Get the folder that contains the XNB. directoryName = Path.GetDirectoryName(fileName); } else if (GameContentBuilder.IsSupportedModelFileExtension(extension)) { // Build the XNB and get the output folder. var buildResult = await Task.Run(() => BuildXnb(Editor.Services, Editor.ApplicationName, fileName, UseDigitalRuneGraphics, recreateModelAndMaterialFiles)); directoryName = buildResult.Item1; _tempDirectoryHelper = buildResult.Item2; } else { throw new EditorException(Invariant($"Unsupported 3D model file format (file extension \"{extension}\").")); } } catch (Exception) { if (IsDisposed) { // Document was closed during loading. Reset(); return; } State = ModelDocumentState.Error; UpdateProperties(); UpdateOutline(); // The GameContentBuilder logs to the output service. _outputService.Show(); throw; } if (IsDisposed) { // Document was closed during loading. Reset(); return; } Debug.Assert(directoryName != null); // ----- Load XNB try { // Get asset name for use with ContentManager. XNBs and unprocessed models // use different folder hierarchies. string assetFileName; if (IsXnb) { // Use absolute path. assetFileName = fileName; } else { // The asset is built relative to the root folder (e.g. "C:\"). The folder // hierarchy (from root to asset) is rebuilt in the temporary output folder. // Make file name relative to root. assetFileName = DRPath.GetRelativePath(Path.GetPathRoot(fileName), fileName); // Get absolute file name relative to temporary output folder. assetFileName = Path.Combine(directoryName, assetFileName); // Change extension. .fbx --> .xnb assetFileName = Path.ChangeExtension(assetFileName, "xnb"); } _monoGameContent = await Task.Run(() => _monoGameService.LoadXnb(directoryName, assetFileName, cacheResult: false)); if (_monoGameContent.Asset is ModelNode) { ModelNode = (ModelNode)_monoGameContent.Asset; UseDigitalRuneGraphics = true; HasAnimations = ModelNode.GetDescendants() .OfType <MeshNode>() .FirstOrDefault()? .Mesh? .Animations? .Count > 0; } else if (_monoGameContent.Asset is Model) { Model = (Model)_monoGameContent.Asset; UseDigitalRuneGraphics = false; HasAnimations = false; // Enable default lighting. var effects = Model.Meshes .SelectMany(m => m.Effects) .OfType <IEffectLights>(); foreach (var effect in effects) { effect.EnableDefaultLighting(); } } else { throw new EditorException("XNB does not contain ModelNode or Model."); } } catch (Exception exception) { Reset(); if (IsDisposed) { return; } State = ModelDocumentState.Error; Logger.Error(exception, "XNB could not be loaded."); // Let LoadAsync return and fail, then show message box. WindowsHelper.BeginInvokeOnUI(() => { var message = Invariant($"XNB could not be loaded:\n\n\"{exception.Message}\""); MessageBox.Show(message, Editor.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error); }); throw; } if (IsDisposed) { // Document was closed during loading. Reset(); return; } // ----- Load Assimp scene try { if (!IsXnb) { _assimpScene = await Task.Run(() => LoadAssimp(fileName)); } } catch (Exception exception) { Logger.Warn(exception, "Assimp could not read model file."); } if (IsDisposed) { // Document was closed during loading. Reset(); return; } State = ModelDocumentState.Loaded; // ----- Validate model ValidateModelNode(); // TODO: Validate MonoGame Model. // If there are errors or warnings, show Output and Errors window. // (Drawback: This steals focus from the document.) //if (_errors.Count > 0) //{ // _outputService?.Show(); // _errorService?.Show(); //} // ----- Update outline and properties UpdateOutline(); UpdateProperties(); }
/// <summary> /// Converts given ms-appdata: URI to filesystem path. /// </summary> /// <param name="appdataUri">ms-appdata: URI.</param> /// <returns>Filesystem path.</returns> public static string ToPath(Uri appdataUri) { if (appdataUri == null) { throw new ArgumentNullException(nameof(appdataUri)); } if (!appdataUri.IsAbsoluteUri) { throw new ArgumentOutOfRangeException(nameof(appdataUri), "URI must be absolute."); } if (!appdataUri.Scheme.Equals(AppdataSchema, StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentOutOfRangeException(nameof(appdataUri), "URI must be ms-appdata."); } if (!string.IsNullOrEmpty(appdataUri.Host)) { // is host is provided, it must be equal to package name if (!appdataUri.Host.Equals(Package.Current.Id.Name, StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentOutOfRangeException(nameof(appdataUri), $"When provided, the URI host must match package name ('{Package.Current.Id.Name}')."); } } var path = appdataUri.AbsolutePath; if (path == string.Empty) { throw new ArgumentOutOfRangeException(nameof(appdataUri), "URI path must not be empty."); } // normalize slash type path = Path.GetFullPath(path); var root = Path.GetPathRoot(path); var relativePath = path.Substring(root.Length); string appDataFolderPath = null; // locate the application data path if (relativePath.StartsWith(LocalFolderRoute, StringComparison.InvariantCultureIgnoreCase)) { appDataFolderPath = ApplicationData.Current.LocalFolder.Path; relativePath = relativePath.Substring(LocalFolderRoute.Length); } else if (relativePath.StartsWith(RoamingFolderRoute, StringComparison.InvariantCultureIgnoreCase)) { appDataFolderPath = ApplicationData.Current.RoamingFolder.Path; relativePath = relativePath.Substring(RoamingFolderRoute.Length); } else if (relativePath.StartsWith(TemporaryFolderRoute, StringComparison.InvariantCultureIgnoreCase)) { appDataFolderPath = ApplicationData.Current.TemporaryFolder.Path; relativePath = relativePath.Substring(TemporaryFolderRoute.Length); } var directorySeparator = Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture); // relative path is now either empty (URI points to the folder itself) or must start with separator to be valid if (appDataFolderPath == null || (relativePath != string.Empty && !relativePath.StartsWith(directorySeparator))) { throw new ArgumentOutOfRangeException(nameof(appdataUri), "URI must point to local, roaming or temp folder"); } // Path.Combine recognizes leading / as root - it needs to be removed first if (relativePath.StartsWith(directorySeparator)) { relativePath = relativePath.Substring(1); } var targetPath = Path.Combine(appDataFolderPath, relativePath); // perform URL decoding - to handle special cases like "ms-appdata://local/Hello%23World.html" return(Uri.UnescapeDataString(targetPath)); }
public static string GetPathRoot(string path) => MSIOP.GetPathRoot(path);