0

当有多个字符时,如何将 IndexOf 与 SubString 一起使用来选择特定字符?这是我的问题。我想采用路径“C:\Users\Jim\AppData\Local\Temp\”并删除“Temp\”部分。只留下“C:\Users\Jim\AppData\Local\”我已经用下面的代码解决了我的问题,但这假设“Temp”文件夹实际上被称为“Temp”。有没有更好的办法?谢谢

if (Path.GetTempPath() != null) // Is it there?{
tempDir = Path.GetTempPath(); //Make a string out of it.
int iLastPos = tempDir.LastIndexOf(@"\");
if (Directory.Exists(tempDir) && iLastPos > tempDir.IndexOf(@"\"))
{
    // Take the position of the last "/" and subtract 4.
    // 4 is the lenghth of the word "temp".
    tempDir = tempDir.Substring(0, iLastPos - 4);
}}
4

4 回答 4

7

更好的方法是使用Directory.GetParent()or DirectoryInfo.Parent

using System;
using System.IO;

class Test
{
    static void Main()
    {
        string path = @"C:\Users\Jim\AppData\Local\Temp\";
        DirectoryInfo dir = new DirectoryInfo(path);
        DirectoryInfo parent = dir.Parent;
        Console.WriteLine(parent.FullName);
    }    
}

(请注意,这Directory.GetParent(path)只是为您提供了 Temp 目录,因为它不理解该路径已经是一个目录。)

如果您真的想使用LastIndexOf,请使用允许您指定起始位置的重载

于 2010-04-13T19:19:58.670 回答
2

为什么不直接使用 System 类来处理呢?

string folder = Environment.GetFolder(Environment.SpecialFolder.LocalApplicationData);
于 2010-04-13T19:21:45.883 回答
1

其他回答者已经展示了实现目标的最佳方式。为了进一步扩展您的知识,我建议您查看正则表达式以满足您的字符串匹配和替换需求,一般来说。

在我自学编程生涯的头几年,我做了可以想象的最复杂的字符串操作,然后我意识到其他人已经解决了所有这些问题,于是我拿起了一本Mastering Regular Expressions。我强烈推荐它。

剥离最后一个目录的一种方法是使用以下正则表达式:

tempDir = Regex.Match(tempDir, @".*(?=\\[^\\]+)\\?").Value;

它可能看起来很神秘,但这实际上会从路径中删除最后一个项目,不管它的名字是什么,也不管\最后是否有另一个项目。

于 2010-04-13T19:41:21.863 回答
0

我会使用 DirectoryInfo 类。

DirectoryInfo tempDirectory = new DirectoryInfo(Path.GetTempPath());            
DirectoryInfo tempDirectoryParent = tempDirectory.Parent;
于 2010-04-13T19:21:57.160 回答