我如何使用的IndexOf与串选择一个特定的字符时,有超过其中一个?这是我的问题。我想借此路径为“C:\用户\吉姆\应用程序数据\本地的\ Temp \”,并删除“TEMP \”的一部分。只留下“C:\用户\吉姆\应用程序数据\本地\”我已经解决了我的问题,下面的代码,但这个假定的“临时”文件夹实际上是所谓的“温度”。有没有更好的办法?感谢

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);
}}
有帮助吗?

解决方案

在更好的方法是使用 Directory.GetParent() 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不过,使用过载,它允许你指定开始地点

其他提示

为什么不直接处理这个直接使用系统类?

string folder = Environment.GetFolder(Environment.SpecialFolder.LocalApplicationData);

在其他回答者显示来实现自己的目标的最佳途径。在进一步扩大自己的知识的兴趣,我建议你看一下你的字符串匹配和更换需求正则表达式,在一般。

我度过了前几年我自学的编程生涯做最令人费解的字符串操作可以想象我才意识到,别人早已经解决了所有这些问题,我拿起的精通正则表达式的。我强烈推荐它。

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

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

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

我会使用DirectoryInfo类。

DirectoryInfo tempDirectory = new DirectoryInfo(Path.GetTempPath());            
DirectoryInfo tempDirectoryParent = tempDirectory.Parent;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top