C# Path

标签:C#Path C-Sharp 
0

Path handles file path processing. The .NET Framework provides effective ways of dealing with filenames and paths. It introduces the Path type in the System.IO namespace. There are complications when dealing directly with paths.

Example

You will often need to extract parts of filename paths in your programs. The .NET Framework team at Microsoft has thought of this problem—the Path class is ideal. You can access it by adding “using System.IO” at the top of your class.

Next: As an introduction, we see a short console program that shows four Path methods.

Console

  1. Program that uses Path methods: C#
  2.  
  3. using System;
  4. using System.IO;
  5.  
  6. class Program
  7. {
  8. static void Main()
  9. {
  10. string path = "C:\\stagelist.txt";
  11.  
  12. string extension = Path.GetExtension(path);
  13. string filename = Path.GetFileName(path);
  14. string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
  15. string root = Path.GetPathRoot(path);
  16.  
  17. Console.WriteLine("{0}\n{1}\n{2}\n{3}",
  18. extension,
  19. filename,
  20. filenameNoExtension,
  21. root);
  22. }
  23. }
  24.  
  25. Output
  26.  
  27. .txt
  28. stagelist.txt
  29. stagelist
  30. C:\

In this example, we take the extension of the file, the actual filename, the filename without the extension, and the path root. The path root is “C:\\”, with the trailing separator, even when the file is nested in many folders.

GetFileName. You can get the filename alone by calling the Path.GetFileName method. This will return the filename at the end of the path, along with the extension, such as .doc or .exe.

Also: There is a method to just get the extension, and one just to get the name with no extension—Path.GetFileNameWithoutExtension.

Example 2

It is useful to see the results of the Path methods on various inputs. Sometimes the methods handle invalid characters as you might expect. Sometimes they do not. This program calls three Path methods on an array of possible inputs.

  1. Program that tests Path class: C#
  2.  
  3. using System;
  4. using System.IO;
  5.  
  6. class Program
  7. {
  8. static void Main()
  9. {
  10. string[] pages = new string[]
  11. {
  12. "cat.aspx",
  13. "really-long-page.aspx",
  14. "test.aspx",
  15. "invalid-page",
  16. "something-else.aspx",
  17. "Content/Rat.aspx",
  18. "http://dotnetperls.com/Cat/Mouse.aspx",
  19. "C:\\Windows\\File.txt",
  20. "C:\\Word-2007.docx"
  21. };
  22. foreach (string page in pages)
  23. {
  24. string name = Path.GetFileName(page);
  25. string nameKey = Path.GetFileNameWithoutExtension(page);
  26. string directory = Path.GetDirectoryName(page);
  27. // // Display the Path strings we extracted. //
  28. Console.WriteLine("{0}, {1}, {2}, {3}",
  29. page, name, nameKey, directory);
  30. }
  31. }
  32. }
  33.  
  34. Output: reformatted
  35.  
  36. Input: cat.aspx
  37. GetFileName: cat.aspx
  38. GetFileNameWithoutExtension: cat
  39. GetDirectoryName: -
  40.  
  41. Input: really-long-page.aspx
  42. GetFileName: really-long-page.aspx
  43. GetFileNameWithoutExtension: really-long-page
  44. GetDirectoryName: -
  45.  
  46. Input: test.aspx
  47. GetFileName: test.aspx
  48. GetFileNameWithoutExtension: test
  49. GetDirectoryName: -
  50.  
  51. Input: invalid-page
  52. GetFileName: invalid-page
  53. GetFileNameWithoutExtension: invalid-page
  54. GetDirectoryName: -
  55.  
  56. Input: Content/Rat.aspx
  57. GetFileName: Rat.aspx
  58. GetFileNameWithoutExtension: Rat
  59. GetDirectoryName: Content
  60.  
  61. Input: http://dotnetperls.com/Cat/Mouse.aspx
  62. GetFileName: Mouse.aspx
  63. GetFileNameWithoutExtension: Mouse
  64. GetDirectoryName: http:\dotnetperls.com\Cat
  65.  
  66. Input: C:\Windows\File.txt
  67. GetFileName: File.txt
  68. GetFileNameWithoutExtension: File
  69. GetDirectoryName: C:\Windows
  70.  
  71. Input: C:\Word-2007.docx
  72. GetFileName: Word-2007.docx
  73. GetFileNameWithoutExtension: Word-2007
  74. GetDirectoryName: C:\

Extensions. GetFileName­WithoutExtension will return the entire file name if there’s no extension on the file.Path.GetDirectoryName returns the entire string except the file name and the slash before it.

Path methods and URLs. Please look at the table above where the directory name of the URL is received. The slashes are reversed into Windows-style slashes. This is not desirable with virtual paths or URLs.

Tip: The volume such as “C:\” is part of the directory name. The directory name doesn’t include the trailing slash “\”.

Syntax

When specifying paths in C# programs, we must use two backslashes “\\” unless we use the verbatim string syntax. A verbatim string uses the prefix character “@”. Only one backslash is needed in this literal syntax.

String Literal

  1. Program that uses verbatim string: C#
  2.  
  3. using System;
  4. using System.IO;
  5.  
  6. class Program
  7. {
  8. static void Main()
  9. {
  10. // ... Verbatim string syntax.
  11. string value = @"C:\directory\word.txt";
  12. Console.WriteLine(Path.GetFileName(value));
  13. }
  14. }
  15.  
  16. Output
  17.  
  18. word.txt

Extensions

The Path type includes also support for extensions. We can get an extension, with GetExtension, or even change an extension with ChangeExtension. The method names are obvious and easy-to-remember.

GetExtension handles extensions of four letters. It also handles the case where a file name has more than one period in it. This next program briefly tests GetExtension. You can find further details and benchmarks.

Path.GetExtension Path.ChangeExtension

  1. Program that uses GetExtension: C#
  2.  
  3. using System;
  4. using System.IO;
  5.  
  6. class Program
  7. {
  8. static void Main()
  9. {
  10. // ... Path values.
  11. string value1 = @"C:\perls\word.txt";
  12. string value2 = @"C:\file.excel.dots.xlsx";
  13.  
  14. // ... Get extensions.
  15. string ext1 = Path.GetExtension(value1);
  16. string ext2 = Path.GetExtension(value2);
  17. Console.WriteLine(ext1);
  18. Console.WriteLine(ext2);
  19. }
  20. }
  21.  
  22. Output
  23.  
  24. .txt
  25. .xlsx

Path.Combine

Path.Combine is a useful method, but there are edge cases it cannot solve. It can’t figure out what you want if what it receives is confusing. But different inputs can yield the same result path.

Next: Here’s a screenshot where we combine the folder “Content\\” with the file name “file.txt”.

The screenshot shows what values Path.Combine produced. It shows that the following two lines of code produce the same result. Path.Combine handles certain cases where you have directory separators in different positions.

  1. Program that uses Path.Combine: C#
  2.  
  3. using System;
  4.  
  5. class Program
  6. {
  7. static void Main()
  8. {
  9. // // Combine two path parts. //
  10. string path1 = System.IO.Path.Combine("Content", "file.txt");
  11. Console.WriteLine(path1);
  12.  
  13. // // Same as above but with a trailing separator. //
  14. string path2 = System.IO.Path.Combine("Content\\", "file.txt");
  15. Console.WriteLine(path2);
  16. }
  17. }
  18.  
  19. Output
  20.  
  21. Content\file.txt
  22. Content\file.txt

The example above also shows how to refer the Path class by specifying “System.IO.Path” instead of including the namespace at the top of your file. This may be useful in source files that are not file-IO oriented.

Tip: When using a C-style language such as C# or C++, you have to add the char \ to your C# code, you must use \\ (two backslashes).

Note: That’s because C# uses the backslash to escape characters, so you must escape it.

ASP.NET paths

The Path class doesn’t work well for URLs or virtual paths, but it is still useful in ASP.NET websites. For each ASP.NET request, there is a Request.PhysicalPath. That value is Windows-style path—it works well with the Path class.

  1. Code that tests extensions: C#
  2.  
  3. // // This could be in your Global.asax file or in an ASPX page. // It gets the physical path. //
  4. string physical = Request.PhysicalPath;
  5. // // Here we see if we are handling an ASPX file. //
  6. if (Path.GetExtension(physical) == ".aspx")
  7. {
  8. // // Get the file name without an extension. //
  9. string key = Path.GetFileNameWithoutExtension(physical);
  10. }

Random file names

Random file names are useful for many programs. If you need to write a temp file or log and you don’t care about the path, use Path.GetRandomFileName. You can use this for random strings, too, but that isn’t its primary purpose.

Path.GetRandomFileName

Tip: Here’s the random string it yielded just now: zd4xcjmo.u4p. No file of that name likely exists.

Separator characters

The Path type also includes two properties for separators. These are good for creating code that is easy to understand, as it is easier for some developers to read Path.DirectorySeparatorChar.

Next: I looked at these two properties in the debugger and the results are shown below.

  1. Path.DirectorySeparatorChar result
  2.  
  3. "\\"
  4.  
  5. Path.AltDirectorySeparatorChar result
  6.  
  7. "/"

Temporary file names

There exist methods for getting temporary file names. When looking at them in the debugger, they point to a “Temp” folder in your User folder. Here are what Visual Studio’s debugger says my temp file names equal.

Note: GetTempPath() has a separator character on the end, unlike Path.GetDirectoryName’s return value.

Path.GetTempPath

  1. Path.GetTempFileName result
  2.  
  3. C:\\Users\\allensamuel\\AppData\\Local\\Temp\\tmpC1D0.tmp
  4. The output file name ends with ".tmp".
  5.  
  6. Path.GetTempPath result
  7.  
  8. C:\\Users\\allensamuel\\AppData\\Local\\Temp\\
  9. The output path ends with the backslash character, \\.

Invalid characters

When accepting input from your user, your program should expect that invalid characters will be entered. For example, your program has a custom file name dialog. You need to quickly detect invalid path characters.

So: You can use the Path.GetInvalidFileNameChars and Path.GetInvalidPathChars methods.

Tip: You can use the character arrays returned by Path.GetInvalidFileNameChars and Path.GetInvalidPathChars with a Dictionary.

ToDictionary

  1. Program that gets invalid characters: C#
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7.  
  8. class Program
  9. {
  10. static void Main()
  11. {
  12. // First, we build a Dictionary of invalid characters.
  13. var dict = GetInvalidFileNameChars();
  14. // Next, we test the dictionary to see if the asterisk (star) is valid.
  15. if (dict.ContainsKey('*'))
  16. {
  17. // This will run, because the star is in the Dictionary.
  18. Console.WriteLine("* is an invalid char");
  19. }
  20. }
  21.  
  22. /// <summary> /// Get a Dictionary of the invalid file name characters. /// </summary>
  23. static Dictionary<char, bool> GetInvalidFileNameChars()
  24. {
  25. // This method uses lambda expressions with ToDictionary.
  26. return Path.GetInvalidFileNameChars().ToDictionary(c => c, c => true);
  27. }
  28. }
  29.  
  30. Output
  31.  
  32. * is an invalid char

Discussion

Path is a powerful class. It can change a file name’s extension. It can determine whether the path is “rooted”—meaning whether it is relative or absolute. You can also get information about the volume, which is usually your hard drive.

Tip: Getting the directory name of your string path is often useful. There are also benchmarks of Path.GetDirectoryName.

Path.GetDirectoryName

We should remember that Path is best used only for certain types of paths. Web addresses are considered paths, but in the .NET Framework they are URIs. And the Uri type—described further down on this page—is best for them.

Warning: I suggest that you don’t use Path for URLs or virtual paths in ASP.NET. The Path type has inconsistencies with directory names.

Also: It doesn’t have lookup tables for invalid characters, so you need to use the array or a Dictionary, such as the one we saw here.

File lists

It is a common requirement to need to get lists of files in certain directories. Also, we show how to get recursive lists of files, by traversing subdirectories. These are not Path methods but they do return path strings.

Directory.GetFiles, Get File List Recursive File List

Misc.

Some custom methods may be helpful when working with the Path class. For example, storing a list of reserved filenames and then testing to see if a filename is reserved can improve certain programs.

Path Exists Reserved Filenames

Optimization: There are ways to optimize the Path methods so that they are more efficient.

But: You must be careful not to change the functionality in ways that are detrimental.

GetFileNameWithout Extension

Uri

The Uri type provides support for website addresses and paths. It contains many helper methods you can use to specify addresses of websites. If a path starts with http, it is a better idea to use Uri.

Uri UriBuilder

Summary

We used Path for Windows-native path manipulations and tests, in the C# language. It is ideal for file names, directory names, relative paths, file name extensions, and invalid character testing.

Thus: These examples hopefully put you on the path to good file path handling in the .NET Framework.

出自:http://www.dotnetperls.com/path

版权信息:长青树>>C# Path
本文链接:http://www.tree360.cn/2013/05/1314.html 转载请注明出处.

C# Path 有关于文件路径等问题类(转)的更多相关文章

  1. C# Path 有关于文件路径获取的问题 的方法

    string Current = Directory.GetCurrentDirectory();//获取当前根目录 //private string strFilePath = Applicatio ...

  2. Android根据文件路径使用File类获取文件相关信息

    Android通过文件路径如何得到文件相关信息,如 文件名称,文件大小,创建时间,文件的相对路径,文件的绝对路径等: 如图: 代码: public class MainActivity extends ...

  3. android--------根据文件路径使用File类获取文件相关信息

    Android通过文件路径如何得到文件相关信息,如 文件名称,文件大小,创建时间,文件的相对路径,文件的绝对路径等. 如图: public class MainActivity extends Act ...

  4. python 文件路径操作方法(转)

    Python编程语言在实际使用中可以帮助我们轻松的实现一些特殊的功能需求.在这里我们将会为大家详细介绍一下有关Python文件路径的相关操作技巧,从而方便我们在实际开发中获得一些帮助. Python文 ...

  5. Mac automator bash 自动操作 右键菜单unrar解压 拷贝文件路径到剪贴板 快速删除(rm -rf) 快捷键设置

    https://tecadmin.net/pass-command-line-arguments-in-shell-script/ https://tecadmin.net/tutorial/bash ...

  6. [LeetCode] Longest Absolute File Path 最长的绝对文件路径

    Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsub ...

  7. nginx之七:nginx path(root)文件路径配置

    nginx指定文件路径有两种方式root和alias,这两者的用法区别,使用方法总结了如下,方便大家在应用过程中,快速响应.root和alias主要区别在于如何解释location后面的uri,这会使 ...

  8. Linux 中C/C++ search path(头文件搜索路径)

    https://blog.csdn.net/BjarneCpp/article/details/76135980 起因 我拿到了一套Linux下的C++代码,代码中有这个头文件#include < ...

  9. [LeetCode] Simplify Path,文件路径简化,用栈来做

    Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", ...

随机推荐

  1. 利用php生成验证码

    <?php /** * php生成验证码 * @param $width 画布宽 * @param $height 画布高 * @param $vcodelen 验证码长度 * @param $ ...

  2. SQL基本操作——通配符

    SQL 通配符:在搜索数据库中的数据时,SQL 通配符可以替代一个或多个字符.SQL 通配符必须与 LIKE 运算符一起使用.在 SQL 中,可使用以下通配符: 通配符 描述 % 替代一个或多个字符 ...

  3. redis查看数据

    目前Redis缓存数据库在许多行业平台大量应用,有效解决了高并发等特定场景的应用性能瓶颈,Redis数据的查看.维护,性能监控有没有好用的工具呢,目前TreeSoft数据库管理系统可以满足实现需求. ...

  4. 谈一谈a:link、a:visited、a:hover、a:active的正确使用顺序

    前端路上,未来还远,所以基础部分必须扎实,走好现在脚下的每一步才是现在最重要的. 下面进入正题吧. 1. <a>标签 我们先说一说<a>标签是干啥用的. <a> 标 ...

  5. vino-server服务是啥服务

    近期接手一个项目,开始梳理服务器,突然发现有个进程是开启5900远程桌面端口的, 在不知情的情况下怕被人给利用了,啥也不说,先干掉再说. server端开启vino-server,允许别人查看自己的桌 ...

  6. zabbix实现163邮件报警

    Zabbix 邮件报警 电脑登录网易邮箱配置,把自己的授权码看一下,并写入配置文件 server端安装配置邮件服务器 [root@server ~]# yum -y install mailx dos ...

  7. CF176E Archaeology(set用法提示)

    题目大意: 给一棵树,每次激活或熄灭一个点,每次问这些点都联通起来所需的最小总边权 分析: 若根据dfs序给所有点排序,为$v1,v2,v3....vk$,那么答案就是$(dis(v1,v2)+dis ...

  8. fuel一键部署

    1. 所需物理主机的要求如下 内存:8GB+,推荐16GB: 磁盘:50GB+: 物理机OS:ubuntu-desktop-amd64 14.04(推荐) 或windows64位 物理机安装软件:安装 ...

  9. php第十三节课

    查询 <?php class DBDA{ public $host = "localhost"; //数据库地址 public $uid = "root" ...

  10. 计蒜客 成绩统计 (Hash表)

    链接 : Here! 思路 : 如果用 $STL$ 的 $map$ 或者是使用 $unordered\underline{}map$ 的话是会 $T$ 的, 所以得手写一个 $hash表$. 其实这个 ...