The method of using relative path to read file in winform in C#

This article mainly introduces the method of Winform in C# to read files using relative paths. An example analyzes the skills and practical applications of C# using relative paths to read files. Friends who need it can refer to

The example in this article describes how winform uses relative paths to read files in C#. Share it with everyone for your reference. The specific analysis is as follows:

The directory structure is shown in the figure below:

Method 1: Since the generated exe file is in the bin\debug directory, the xml file to be read can be obtained by looking up the directory

Copy the code as follows:
string haarXmlPath = @"…/…/haarcascade_frontalface_alt_tree.xml";

FileInfo file = new FileInfo(fileName);

string fullName = file.FullName;

Method 2: Obtain the path of the exe file for interception, do it twice, and then concatenate the file name to form the full path

Copy the code as follows:
string haarXmlPath = @"haarcascade_frontalface_alt_tree.xml";

string fullName = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("\"));

fullName = fullName.Substring(0, fullName.LastIndexOf("\")) + “\” + haarXmlPath;

another way:

Copy the code code as follows:

///
/// 获取应用程序根路径
///
private static string GetApplicationPath()
{
string path = Application.StartupPath;
//string path=AppDomain.CurrentDomain.BaseDirectory; //另一种获取方式
string folderName = String.Empty;
while (folderName.ToLower() != “bin”)
{
path = path.Substring(0, path.LastIndexOf("\"));
folderName = path.Substring(path.LastIndexOf("\") + 1);
}
return path.Substring(0, path.LastIndexOf("\") + 1);
}

Guess you like

Origin blog.csdn.net/s_156/article/details/113929986