I have a folder with files coming in as
fileName(prefix) + " " + todayDate.ToString("yyyyMMdd") + ".csv";
For simple file my regex was FilePrefix + #"(.*)\.csv"
How to have a search pattern to get file for only today's date ?
It sounds like if you're just searching for today's date, then you should already know exactly what file name you're looking for. So there's no need for a regex - just look for files where
var expectedName = FilePrefix + " " + DateTime.Now.ToString("yyyyMMdd") + ".csv";
String.Compare(fileName, expectedName, StringComparison.OrdinalIgnoreCase) == 0
Just do something like this
List<string> fileNames = // wherever you're getting these
var ending = DateTime.Now.ToString("yyyyMMdd") + ".csv";
var filteredFileNames = fileNames.Where(x => x.EndsWith(ending));
Related
I have successfully regex matched multiple string from a folder with txt.files with "streamreader" but i also need to obtain the matched string's file path.
How am i able to obtain the matched string's file paths?
static void abnormalitiescheck()
{
int count = 0;
Regex regex = new Regex(#"(#####)");
DirectoryInfo di = new DirectoryInfo(txtpath);
Console.WriteLine("No" + "\t" + "Name and location of file" + "\t" + "||" +" " + "Abnormal Text Detected");
Console.WriteLine("=" + "\t" + "=========================" + "\t" + "||" + " " + "=======================");
foreach (string files in Directory.GetFiles(txtpath, "*.txt"))
{
using (StreamReader reader = new StreamReader(files))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Match match = regex.Match(line);
if (match.Success)
{
count++;
Console.WriteLine(count + "\t\t\t\t\t" + match.Value + "\n");
}
}
}
}
}
If possible , i want to have output of the strings's file path as well.
For e.g.,
C:/..../email_4.txt
C:/..../email_7.txt
C:/..../email_8.txt
C:/..../email_9.txt
As you already have the DirectoryInfo, you could get the FullName property.
You also have the filename called files. To get the name and location of the file, you could use Path.Combine
Your updated code could look like:
Console.WriteLine(count + "\t" + Path.Combine(di.FullName , Path.GetFileName(files)) + "\t" + match.Value + "\n");
I'm guessing that we might just want to maybe match some .txt files. If that might be the case, let's start with a simple expression that would collect everything from the start of our input strings up to .txt, then we add .txt as a right boundary:
^(.+?)(.txt)$
Demo
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"^(.+?)(.txt)$";
string input = #"C:/..../email_4.txt
C:/..../email_7.txt
C:/..../email_8.txt
C:/..../email_9.txt";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
I am currently working on a project that sweeps a mailbox for attachments and when one is found it is placed in the user's directory. My problem is that when I check if the file exist in the path, I alter the attachment's name and add a counter and time stamp, that way it is not over written. However, when it goes into the condition and changes the file name it never updates the path variable to include the right value of the Clean name variable.
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
string path = employeeStarPath + "\\" + cleanName;
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
Now I am aware I can update the path var by calling path = employeeStarPath + "\\" + cleanName; again but I feel that this makes my code a bit confusing.
I might not understood your question but can you just call the line "string path = employeeStarPath + "\" + cleanName;" at the end instead before the if?
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
string path = employeeStarPath + "\\" + cleanName;
I am trying to use a basic if else case, but the if is executed no matter what.
This is the code found in the backend, on the aspx.cs file.
if (1==2)
{
// 22/09/2014 12:00:00 AM for en
//format date for submit
Dateformatted = this.DateField.Value.ToString();
DateSplit = Dateformatted.Split('/');
yearAt0 = DateSplit[2].Split(' ');
Datetosubmit = yearAt0[0] + "/" + DateSplit[1] + "/" + DateSplit[0] + " 00:00:00";
}
else
{
// 2014-09-22 00:00:00 for fra
//format date for submit
Dateformatted = this.DateField.Value.ToString();
DateSplit = Dateformatted.Split('-');
dayAt0 = DateSplit[2].Split(' ');
Datetosubmit = DateSplit[0] + "/" + DateSplit[1] + "/" + dayAt0[0] + " 00:00:00";
}
This is the error I get (line 1209 is red):
System.IndexOutOfRangeException: Index was outside the bounds of the array.
Line 1207: string Dateformatted = this.DateFieldEdit.Value.ToString();
Line 1208: string[] DateSplit = Dateformatted.Split('/');
Line 1209: string[] yearAt0 = DateSplit[2].Split(' ');
Line 1210: string Datetosubmit = yearAt0[0] + "/" + DateSplit[1] + "/" + DateSplit[0] + " 00:00:00";
Line 1211:
This clearly indicates that the code inside the false part of the if statement was executed. Is there a reason for this? How can I fix this?
Note: The if (1==2) was added to simplify the example, it is normally a parameter
You can see this effect if your binaries and your PDB files are out of sync. If you are using the updated PDBs, but the old binaries, that would definitely explain this scenario.
The easiest way to fix this to to completely clean and rebuild everything. Deleting everything in your bin and obj folders for good measure. You should also restart the IIS instance you are using.
I need to remove a pattern from a string, I think regex could do the job, but I'm having trouble solving this.
The pattern must be in the end of the string.
string fileName = "File (123)";
string pattern = " (0)";
string cleanName = PatternRemover(fileName, pattern);
//Should result in: cleanName == "File"
Edit:
Ok, here is the code that I'm using now after your answers:
public static string GetNextFilePath2(string fullPath, ref uint id, string idFormat)
{
string dir = Path.GetDirectoryName(fullPath);
string ext = Path.GetExtension(fullPath);
string fileNameNoExt = Path.GetFileNameWithoutExtension(fullPath);
if (ext.Length > 0 && ext[0] != '.')
ext = "." + ext;
string baseName = Regex.Replace(fileNameNoExt, #"\s\(\d+\)", "");
string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
string path = Path.Combine(dir, fileName);
while (File.Exists(path))
{
id++;
fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
path = Path.Combine(dir, fileName);
}
return path;
}
It works, but:
It always start to count from id, I think it may be better to start
from the file name number.
I was hopping to use something like "(0)" as a method parameter that would indicate the pattern to be removed and also the "(" would be parametrized. I'm doing it "manually" now on this line: string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
You can do that without REGEX like:
string newFileName = new String(fileName
.Where(r => !char.IsDigit(r)
&& r != '('
&& r != ')'
&& r != ' ').ToArray());
This would give you File.jpg
If you only want to get the file name then you can use:
string fileNameWithoutPath = Path.GetFileNameWithoutExtension(newFileName);
// it would give you `File`
Using regex:
var subject = "File (123).jpg";
var fileNameWithExtension = Regex.Replace(subject,#"\s*\(\d+\)","");
var fileNameWithoutPath = Path.GetFileNameWithoutExtension(fileNameWithExtension);
And thanks for #habib, I'd not have come with Path.GetFileNameWithoutExtension in this for stripping the extension.
You could use:
\s\(\d+\)\.jpg
assuming you do actually want the extension removed and the extension is always ".jpg". Otherwise:
\s\(\d+\)
Looks for a set of digits in brackets proceeded by a space.
I want to save my text file in a F drive but this file is written to a default folder of program . How to save it by guiding a path
string[] contents = new string[2];
contents[0] = "Name: " + textBox1.Text;
contents[1] = "age: " + textBox2.Text;
string path = #"F:\\"; // path to file
System.IO.File.WriteAllLines(textBox1.Text + ".txt", contents);
It would be a good idea to actually use your path variable:
string path = System.IO.Path.Combine(#"F:\", textBox1.Text + ".txt");
System.IO.File.WriteAllLines(path, contents);
Because you defining a path,but you don't use it.
string path = #"F:\" + textBox1.Text + ".txt";
File.WriteAllLines(path, contents);
As an alternative, you can use File.Move after you created it like;
File.WriteAllLines(textBox1.Text + ".txt", contents);
File.Move(Directory.GetCurrentDirectory() + textBox1.Text + ".txt",
path + textBox1.Text + ".txt");