Jim*_*Del 0 c# string substring indexof
当有多个特定字符时,如何使用SubString的IndexOf来选择特定字符?这是我的问题.我想采取路径"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);
}}
Run Code Online (Sandbox Code Playgroud)
更好的方法是使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
(注意,Directory.GetParent(path)只提供Temp目录,因为它不明白该路径已经是一个目录.)
如果您确实想要使用LastIndexOf,请使用允许您指定起始位置的重载.