I want to loop through each file in a folder and save the substring of the file name to a variable.
For example lets say I have the following file in a folder:
ERISRequest_INC1234567.csv //Should Print -> INC1234567
ERISRequest_INC8901234.csv //Should print -> INC8901234
fileName.csv //should skip this one
I want to extract the shown substring if and only if the file name starts with ERISRequest_ and store it in a variable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileName
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(@"C:\");
foreach(FileInfo fi in di.GetFiles())
{
Console.WriteLine(fi.Name);
}
Console.ReadLine();
}
}
}
Get the file name without the extension and then check it starts with your prefix.
using System;
using System.IO;
namespace Quicky
{
class Program
{
static void Main(string[] args)
{
const string PREFIX = "ERISRequest_";
DirectoryInfo di = new DirectoryInfo(@"C:\");
foreach (FileInfo fi in di.GetFiles())
{
if (fi.Name.StartsWith(PREFIX))
{
Console.WriteLine(Path.GetFileNameWithoutExtension(fi.Name).Substring(PREFIX.Length));
}
}
}
}
}
It helps you. Is that what you're looking for?
Regex regex = new Regex(@"ERISRequest_(?<val>[a-zA-Z0-9]{1,})");
DirectoryInfo di = new DirectoryInfo(@"C:\");
foreach (FileInfo fi in di.GetFiles())
{
var match = regex.Match(Path.GetFileNameWithoutExtension(fi.Name));
if (match.Success)
{
Console.WriteLine(match.Groups["val"].Value);
}
}
Console.ReadLine();
EDITED Now, Try this, in C#.
Regex regex = new Regex(@"ERISRequest_(?<val>[a-zA-Z0-9]{1,})");
DirectoryInfo di = new DirectoryInfo(@"C:\");
foreach (FileInfo fi in di.GetFiles())
{
var match = regex.Match(Path.GetFileNameWithoutExtension(fi.Name));
if (match.Success)
{
Console.WriteLine(match.Groups["val"].Value);
}
}
Console.ReadLine();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.