Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取与应用程序域路径位于同一目录中的文件夹_C#_Asp.net - Fatal编程技术网

C# 获取与应用程序域路径位于同一目录中的文件夹

C# 获取与应用程序域路径位于同一目录中的文件夹,c#,asp.net,C#,Asp.net,我有一个asp.net web应用程序,我需要获取与我的web应用程序位于同一目录中的文件夹的字符串路径。 当前我正在使用此代码获取添加域路径 string appPath = HttpRuntime.AppDomainAppPath; 它返回“c:/path/webapp”,我需要“c:/path/folder” 谢谢。您可以使用这个方法 返回一个新字符串,其中指定字符串的所有匹配项 当前实例将替换为另一个指定的字符串 这是一本书 多亏了DonBoitnott的评论,以下是正确的答案 str

我有一个asp.net web应用程序,我需要获取与我的web应用程序位于同一目录中的文件夹的字符串路径。 当前我正在使用此代码获取添加域路径

string appPath = HttpRuntime.AppDomainAppPath;
它返回“c:/path/webapp”,我需要“c:/path/folder”

谢谢。

您可以使用这个方法

返回一个新字符串,其中指定字符串的所有匹配项 当前实例将替换为另一个指定的字符串

这是一本书

多亏了DonBoitnott的评论,以下是正确的答案

string appPath = @"C:\mydir\anotherdir\webapp\thirddir\webapp";
int LastIndex = appPath.LastIndexOf("webapp", StringComparison.InvariantCulture);
string RealappPath = Path.Combine(appPath.Substring(0, LastIndex), "folder");
Console.WriteLine(RealappPath);
这将打印

C:\mydir\anotherdir\webapp\thirddir\folder

如果您想要一种不需要知道起始文件夹的更通用的方法:

//NOTE:  using System.IO;
String startPath = Path.GetDirectoryName(HttpRuntime.AppDomainAppPath);
Int32 pos = startPath.LastIndexOf(Path.DirectorySeparatorChar);
String newPath = Path.Combine(startPath.Substring(0, pos), "folder");  //replace "folder" if it's really something else, of course

这样,无论您的web应用程序从哪个目录运行,您都可以获取该目录,将其降低一级,并添加“文件夹”以获取新的同级目录。

如果路径上有同名文件夹,该目录也会更改。@StylesYoung更改是什么意思?你的目的是什么?我想他的意思是你把它看得太字面了…路径可能并不总是字面上的“C:\path\webapp”…它可能是“C:\mydir\anotherdir\webapp\thirddir\webapp”。在您的解决方案中,该路径被String.Replace()破坏。@DonBoitnott因此,如果它是
“C:\mydir\anotherdir\webapp\thirddir\webapp”
OP不希望结果是
“C:\mydir\anotherdir\folder\thirddir\folder”
?或者仍然想要
c:/path/folder
?@SonerGönül如果应用程序路径是“c:\mydir\anotherdir\webapp\thirddir\webapp”,OP希望文件夹路径是“c:\mydir\anotherdir\webapp\thirddir\folder”。如果我必须在我的webapp中使用类库。在类库中,我必须获得webb应用程序域路径。我将如何实现这一点。您是否建议类库将在不了解web应用的上下文中运行?您是否需要HttpRuntime.AppDomainAppPath的替代品?是的,我需要。它将驻留在类库中。@DonBoitnott我需要HttpRuntime.AppDomainAppPath的替代品。你有什么想法吗?@ShawnSouth在我脑海中浮现:System.AppDomain.BaseDirectory或HttpContext.Current?
//NOTE:  using System.IO;
String startPath = Path.GetDirectoryName(HttpRuntime.AppDomainAppPath);
Int32 pos = startPath.LastIndexOf(Path.DirectorySeparatorChar);
String newPath = Path.Combine(startPath.Substring(0, pos), "folder");  //replace "folder" if it's really something else, of course