C# Path 有关于文件路径等问题类(转)
C# Path
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.
Program that uses Path methods: C# using System;
using System.IO; class Program
{
static void Main()
{
string path = "C:\\stagelist.txt"; string extension = Path.GetExtension(path);
string filename = Path.GetFileName(path);
string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
string root = Path.GetPathRoot(path); Console.WriteLine("{0}\n{1}\n{2}\n{3}",
extension,
filename,
filenameNoExtension,
root);
}
} Output .txt
stagelist.txt
stagelist
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.
Program that tests Path class: C# using System;
using System.IO; class Program
{
static void Main()
{
string[] pages = new string[]
{
"cat.aspx",
"really-long-page.aspx",
"test.aspx",
"invalid-page",
"something-else.aspx",
"Content/Rat.aspx",
"http://dotnetperls.com/Cat/Mouse.aspx",
"C:\\Windows\\File.txt",
"C:\\Word-2007.docx"
};
foreach (string page in pages)
{
string name = Path.GetFileName(page);
string nameKey = Path.GetFileNameWithoutExtension(page);
string directory = Path.GetDirectoryName(page);
// // Display the Path strings we extracted. //
Console.WriteLine("{0}, {1}, {2}, {3}",
page, name, nameKey, directory);
}
}
} Output: reformatted Input: cat.aspx
GetFileName: cat.aspx
GetFileNameWithoutExtension: cat
GetDirectoryName: - Input: really-long-page.aspx
GetFileName: really-long-page.aspx
GetFileNameWithoutExtension: really-long-page
GetDirectoryName: - Input: test.aspx
GetFileName: test.aspx
GetFileNameWithoutExtension: test
GetDirectoryName: - Input: invalid-page
GetFileName: invalid-page
GetFileNameWithoutExtension: invalid-page
GetDirectoryName: - Input: Content/Rat.aspx
GetFileName: Rat.aspx
GetFileNameWithoutExtension: Rat
GetDirectoryName: Content Input: http://dotnetperls.com/Cat/Mouse.aspx
GetFileName: Mouse.aspx
GetFileNameWithoutExtension: Mouse
GetDirectoryName: http:\dotnetperls.com\Cat Input: C:\Windows\File.txt
GetFileName: File.txt
GetFileNameWithoutExtension: File
GetDirectoryName: C:\Windows Input: C:\Word-2007.docx
GetFileName: Word-2007.docx
GetFileNameWithoutExtension: Word-2007
GetDirectoryName: C:\
Extensions. GetFileNameWithoutExtension 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.
Program that uses verbatim string: C# using System;
using System.IO; class Program
{
static void Main()
{
// ... Verbatim string syntax.
string value = @"C:\directory\word.txt";
Console.WriteLine(Path.GetFileName(value));
}
} Output 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
Program that uses GetExtension: C# using System;
using System.IO; class Program
{
static void Main()
{
// ... Path values.
string value1 = @"C:\perls\word.txt";
string value2 = @"C:\file.excel.dots.xlsx"; // ... Get extensions.
string ext1 = Path.GetExtension(value1);
string ext2 = Path.GetExtension(value2);
Console.WriteLine(ext1);
Console.WriteLine(ext2);
}
} Output .txt
.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.
Program that uses Path.Combine: C# using System; class Program
{
static void Main()
{
// // Combine two path parts. //
string path1 = System.IO.Path.Combine("Content", "file.txt");
Console.WriteLine(path1); // // Same as above but with a trailing separator. //
string path2 = System.IO.Path.Combine("Content\\", "file.txt");
Console.WriteLine(path2);
}
} Output Content\file.txt
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.
Code that tests extensions: C# // // This could be in your Global.asax file or in an ASPX page. // It gets the physical path. //
string physical = Request.PhysicalPath;
// // Here we see if we are handling an ASPX file. //
if (Path.GetExtension(physical) == ".aspx")
{
// // Get the file name without an extension. //
string key = Path.GetFileNameWithoutExtension(physical);
}
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.
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.
Path.DirectorySeparatorChar result "\\" Path.AltDirectorySeparatorChar result "/"
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.GetTempFileName result C:\\Users\\allensamuel\\AppData\\Local\\Temp\\tmpC1D0.tmp
The output file name ends with ".tmp". Path.GetTempPath result C:\\Users\\allensamuel\\AppData\\Local\\Temp\\
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.
Program that gets invalid characters: C# using System;
using System.Collections.Generic;
using System.IO;
using System.Linq; class Program
{
static void Main()
{
// First, we build a Dictionary of invalid characters.
var dict = GetInvalidFileNameChars();
// Next, we test the dictionary to see if the asterisk (star) is valid.
if (dict.ContainsKey('*'))
{
// This will run, because the star is in the Dictionary.
Console.WriteLine("* is an invalid char");
}
} /// <summary> /// Get a Dictionary of the invalid file name characters. /// </summary>
static Dictionary<char, bool> GetInvalidFileNameChars()
{
// This method uses lambda expressions with ToDictionary.
return Path.GetInvalidFileNameChars().ToDictionary(c => c, c => true);
}
} Output * 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.
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.
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.
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 有关于文件路径等问题类(转)的更多相关文章
- C# Path 有关于文件路径获取的问题 的方法
string Current = Directory.GetCurrentDirectory();//获取当前根目录 //private string strFilePath = Applicatio ...
- Android根据文件路径使用File类获取文件相关信息
Android通过文件路径如何得到文件相关信息,如 文件名称,文件大小,创建时间,文件的相对路径,文件的绝对路径等: 如图: 代码: public class MainActivity extends ...
- android--------根据文件路径使用File类获取文件相关信息
Android通过文件路径如何得到文件相关信息,如 文件名称,文件大小,创建时间,文件的相对路径,文件的绝对路径等. 如图: public class MainActivity extends Act ...
- python 文件路径操作方法(转)
Python编程语言在实际使用中可以帮助我们轻松的实现一些特殊的功能需求.在这里我们将会为大家详细介绍一下有关Python文件路径的相关操作技巧,从而方便我们在实际开发中获得一些帮助. Python文 ...
- Mac automator bash 自动操作 右键菜单unrar解压 拷贝文件路径到剪贴板 快速删除(rm -rf) 快捷键设置
https://tecadmin.net/pass-command-line-arguments-in-shell-script/ https://tecadmin.net/tutorial/bash ...
- [LeetCode] Longest Absolute File Path 最长的绝对文件路径
Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsub ...
- nginx之七:nginx path(root)文件路径配置
nginx指定文件路径有两种方式root和alias,这两者的用法区别,使用方法总结了如下,方便大家在应用过程中,快速响应.root和alias主要区别在于如何解释location后面的uri,这会使 ...
- Linux 中C/C++ search path(头文件搜索路径)
https://blog.csdn.net/BjarneCpp/article/details/76135980 起因 我拿到了一套Linux下的C++代码,代码中有这个头文件#include < ...
- [LeetCode] Simplify Path,文件路径简化,用栈来做
Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", ...
随机推荐
- 【译】x86程序员手册17-第6章保护
Chapter 6 Protection 第六章 保护 6.1 Why Protection? 为什么要保护? The purpose of the protection features of th ...
- smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp
报错信息 smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp7,DsmowAA3uguL7e1cyvkyFw--.22553S3 1559096715,ple ...
- CAD在网页中增加一个射线
主要用到函数说明: IMxDrawBlockTableRecord::AddRay 向记录中增加一个射线,详细说明如下: 参数 说明 point1 射线上的点1 point2 射线上的点2 js代码实 ...
- BZOJ 1941: [Sdoi2010]Hide and Seek KDtree + 估价函数
Code: #include<bits/stdc++.h> #define maxn 200000 #define inf 1000000000 using namespace std; ...
- [SQL Service]从一张表取值更新另一张表字段
1. update table_A set table_A_column = ab.column from table_A aa left join table_B ab on aa.xx = ab ...
- 57 和为S的数字
题目一:和为S的两个数字 输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的. 输出描述: 对应每个测试案例,输出两个数,小 ...
- python爬虫18 | 就算你被封了也能继续爬,使用IP代理池伪装你的IP地址,让IP飘一会
我们上次说了伪装头部 ↓ python爬虫17 | 听说你又被封 ip 了,你要学会伪装好自己,这次说说伪装你的头部 让自己的 python 爬虫假装是浏览器 小帅b主要是想让你知道 在爬取网站的时候 ...
- java 同时安装多版本问题
java 同时安装多版本问题(转) http://www.cnblogs.com/SamuelSun/p/6022296.html http://blog.csdn.net/u013256622/ar ...
- Codeforces Round #411(Div. 2)——ABCDEF
30min水掉前面4T,30min尝试读懂EF题,60min划水 顺便D忘记取膜丢50分,距比赛结束10s时hack失败丢50分... 从2620掉分到2520,从rank227掉到rank354.. ...
- java后台处理解析json字符串的两种方式
简单说一下背景 上次后端通过模拟http请求百度地图接口,得到的是一个json字符串,而我只需要其中的某个key对应的value. 当时我是通过截取字符串取的,后来觉得不太合理,今天整理出了两种处理解 ...