search
HomeBackend DevelopmentC#.Net TutorialC# program to get file name from absolute path

C# program to get file name from absolute path

introduce

Let us try to understand C# program to get file name from absolute path. We will see the usage of GetFileName method under File class which is used to get the file name and another method GetFileNameWithoutExtension which will return the file name of the specified path string without extension. To get a relative path from two absolute paths, we will use the Uri class in C#. The Uri class provides several methods for working with URIs, including MakeRelativeUri, which we'll use in our code.

A file is a location used in C# to store some information. A collection of files is called a directory. In C#, files belong to the System.IO namespace, which also includes other classes for performing operations on files. Path is another class under the same namespace. There are two types of paths, absolute paths and relative paths. An absolute path includes all the information needed to locate a file or directory on your system. An example of an absolute path is C:\Program Files\Google Chrome\filename.exe.

The relative path tells us the path of the file relative to the current directory the user is working in. Consider the similar example mentioned above, if the main executable is located in C:\Program Files, the relative path to filename.exe is Google Chrome\filename.exe.

GetFileName method

This is a method under the file class in C#, used to get the file name from the absolute path. path.GetFileName is used to perform this operation. It takes an absolute path as input and returns the filename and extension of the specified path. The absolute path used as input is in string form.

grammar

public static string GetFileName(string path)

The path here is the string we need to get the file name from.

In the above example, GetFileName is a method of the path class. This method returns the characters after the last directory character separator in the pathname. If it does not exist, then it will return a NULL value. It also returns a NULL value if the last character of the path is a directory or volume separator.

Similarly, if the path is null, then it will return a NULL value.

If the file name is "C:\mydir\filename.exe", then the output result is filename.exe

algorithm

The algorithm below will give the step-by-step process of getting the file name using the File.GetFileName() method.

For example, if we need to find the name of a file, we can use the following algorithm to understand:

Step 1 Create a string to store the name of the file path. Remember that this is an absolute path.

Step 2 Create an initially empty string file name.

Step 3 We will store the output of the GetFileName method in the string file name.

Step 4 Since the file name in the above code is "myfile", the output will be the same.

Step 5 If the path is null in any case, the returned output will also be NULL.

Step 6 By using the GetFileName method, we can return the name of the file from the absolute path.

Example

using System;
using System.IO;
using System.Text;

class FileName {
   static void Main(string[] args) {
      //declaring the string path.
      string path = "E://Jinku Hu//Starting Over//Csharp//myfile.md";
      
      //declaring the string filename.
      string filename = null;
      
      //we will be storing the value in the filename variable.
      filename = Path.GetFileName(path);
      Console.WriteLine(filename);
      Console.ReadLine();
   }
}

Output

myfile.md

time complexity

In the above mentioned code, we can observe that there are no loops or nested loops inside the main function, so the time complexity is simply O(1).

GetFileNameWithoutExtension method

The method explained before is to use the GetFileName method to return the name of the file. Now we will see how to return the file name without extension. Assuming the name of the path is "C:\Program Files\Google Chrome\filename.exe", then the returned output is "filename". It accepts absolute paths as input and returns filenames as output. The absolute path entered is in the form of a string. Syntax - "public static string GetFileName(string path)", where path is the string we want to get the file name without extension.

In the above example, GetFileName is a method of the path class. This method will return the characters after the last directory character separator in the pathname, without extension. If it does not exist, then it will return a NULL value. It also returns a NULL value if the last character of the path is a directory or volume separator.

算法

在此算法中,我们将了解使用 GetFileNameWithoutExtension 方法返回不带扩展名的文件名的分步方法。

第 1 步  创建一个字符串来存储绝对路径的名称。

步骤2  创建另一个名为filename的字符串,该字符串将作为输出返回。

第三步 − 字符串变量filename将以null作为其初始值。

第四步  使用GetFileNameWithoutExtension方法生成的输出将存储在一个字符串filename中。

步骤 5  如果文件为空,则输出也将相同。

第 6 步 − 因此我们可以使用 GetFileNameWithoutExtension 方法返回不带扩展名的文件名。

示例

using System;
using System.IO;
using System.Text;

class FileName {
   static void Main(string[] args) {
      //declare the string path first.
      string path = "C:\Program Files\Google Chrome\filename.exe";
      
      //declare the string filename and store null initially.
      string filename = null;
      filename = Path.GetFileNameWithoutExtension(path);
      
      //store the answer in the variable filename.
      Console.WriteLine(filename);
      Console.ReadLine();
   }
}

输出

filename.exe

时间复杂度

在上述代码中,我们可以观察到只使用了一种直接生成输出并将其存储在相应变量中的方法。没有使用任何循环或任何类型的复杂递归函数。这仅仅构成了时间复杂度为O(1)。

结论

在本文中,我们广泛讨论了使用GetFileName方法从绝对路径中获取带有扩展名的文件名,以及使用GetFileNameWithoutExtension方法获取不带扩展名的文件名的C#程序。

我们希望本文能够帮助您增强有关 C# 的知识。

The above is the detailed content of C# program to get file name from absolute path. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.