c#中字符串提取的混乱

本文关键字:混乱 提取 字符串 | 更新日期: 2023-09-27 18:04:48

我正在开发一个windows应用程序。

在这里,我从计算机上的任意路径上传一个文件。

我想从中得到文件名。

我使用了>> string name = openFileDialog1.FileName;

我得到的文件名与完整的路径。表示结果如下>>

"C:''Documents and Settings''Administrator''Desktop''15030000.md"

15030000。Md是我的文件名。我只想从中提取前4个字符。即1503[因为它表示日期和月份]。

为此我尝试了substring函数。但后来意识到,完整路径可以是任何东西。我不能使用子字符串函数从"C:''Documents and Settings''Administrator''Desktop''15030000.md"中提取1503

有解决办法吗?

c#中字符串提取的混乱

使用路径。GetFileNameWithoutExtension来获取文件名,之后您可以使用string。子字符串或枚举。取前4个字符。

string fileName = Path.GetFileNameWithoutExtension(path);
string firstFourCharacters = fileName.Take(4);
//Or 
//Check if the fileName.Length >= 4
string firstFourCharacters = fileName.Substring(0,4);