Is there any easy way to isolate the last 2 elements of the path (basedir + filename) in C# or do I need to make some complex string regex? All examples I found online show either isolating the filename, or the full path minus filename.
Example of the input:
string1 = C:\dir\example\1\test.txt
string2 = C:\dir\example\2\anotherdir\example\file.ext
string3 = /mnt/media/hdd/test/1/2/3/4/dir/file
Expected output:
string1cut = 1\test.txt
string2cut = example\file.ext
string3cut = dir/file
You can do this:
string path = #"C:\dir\example\1\test.txt";
string path2 = #"/mnt/media/hdd/test/1/2/3/4/dir/file";
string lastFolderName =
Path.GetFileName(Path.GetDirectoryName(path));
string fileName = Path.GetFileName(path);
string envPathChar = path.Contains("/") ? "/" : #"\";
string string1Cut = #$"{lastFolderName}{envPathChar}{fileName}";
outputs : 1\test.txt
path2 outputs : dir/file
Related
I have a string (from a filename) like this: Mytext_edit1345.jpg
I just want to cut the "_edit1345" so I can get Mytext.jpg as a result.
Is Regex.Replace the best way to go for me?
string result = Regex.Replace(Bildname, pattern, "");
What pattern do i need?
You can use the Path class and string methods like String.Remove
string fileNameWOE = Path.GetFileNameWithoutExtension(fileName);
int indexOfUnderscore = fileNameWOE.IndexOf('_');
if(indexOfUnderscore >= 0)
fileNameWOE = fileNameWOE.Remove(indexOfUnderscore);
fileName = fileNameWOE + Path.GetExtension(fileName);
Use String.Substring with Path.GetExtension like:
string fileName = "Mytext_edit1345.jpg";
string newFileName = fileName;
if (fileName.Contains('_'))
{
newFileName = fileName.Substring(0, fileName.IndexOf('_')) +
Path.GetExtension(fileName);
}
Use the below pattern to match the substring(from_ upto the next .) you want to cut-down,
_[^.]*
DEMO
Your code would be,
string str = "Mytext_edit1345.jpg";
string result = Regex.Replace(str, #"_[^.]*", "");
Console.WriteLine(result);
Console.ReadLine();
IDEONE
I have a string that defines the path of a file:
string duplicateFilePath = D:\User\Documents\processed\duplicate_files\file1.jpg;
I am going to move a file to this location but sometimes a file with the identical name exists all ready. In this case I want to differentiate the filename. I have the crc value of each file available so I figured that may be good to use to ensure individual file names. I can create:
string duplicateFilePathWithCrc = duplicateFilePath + "(" + crcValue + ")";
But this gives:
D:\User\Documents\processed\duplicate_files\file1.jpg(crcvalue);
and I need:
D:\User\Documents\processed\duplicate_files\file1(crcvalue).jpg;
How can I put the crcvalue into the string before the file extension, bearing in mind there could be other .'s in the file path and file extensions vary?
Use the static methods in the System.IO.Path class to split the filename and add a suffix before the extension.
string AddSuffix(string filename, string suffix)
{
string fDir = Path.GetDirectoryName(filename);
string fName = Path.GetFileNameWithoutExtension(filename);
string fExt = Path.GetExtension(filename);
return Path.Combine(fDir, String.Concat(fName, suffix, fExt));
}
string newFilename = AddSuffix(filename, String.Format("({0})", crcValue));
int value = 42;
var path = #"D:\User\Documents\processed\duplicate_files\file1.jpg";
var fileName = String.Format("{0}({1}){2}",
Path.GetFileNameWithoutExtension(path), value, Path.GetExtension(path));
var result = Path.Combine(Path.GetDirectoryName(path), fileName);
Result:
D:\User\Documents\processed\duplicate_files\file1(42).jpg
Something like this
string duplicateFilePath = #"D:\User\Documents\processed\duplicate_files\file1.jpg";
string crcValue = "ABCDEF";
string folder = Path.GetDirectoryName(duplicateFilePath);
string filename = Path.GetFileNameWithoutExtension(duplicateFilePath);
string extension = Path.GetExtension(duplicateFilePath);
string newFilename = String.Format("{0}({1}){2}", filename, crcValue, extension);
string path_with_crc = Path.Combine(folder,newFilename );
This can also be achieved by using Replace:
using System.IO;
string duplicateFilePathWithCrc = duplicateFilePath.Replace(
Path.GetFileNameWithoutExtension(duplicateFilePath),
Path.GetFileNameWithoutExtension(duplicateFilePath + "(" + crcValue + ")"),
);
Try using the Path class (it's in the System.IO namespace):
string duplicateFilePathWithCrc = Path.Combine(
Path.GetDirectoryName(duplicateFilePath),
string.Format(
"{0}({1}){2}",
Path.GetFileNameWithoutExtension(duplicateFilePath),
crcValue,
Path.GetExtension(duplicateFilePath)
)
);
Getting this error The given path's format is not supported. at this line
System.IO.Directory.CreateDirectory(visit_Path);
Where I am doing mistake in below code
void Create_VisitDateFolder()
{
this.pid = Convert.ToInt32(db.GetPatientID(cmbPatientName.SelectedItem.ToString()));
String strpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = strpath + "\\Patients\\Patient_" + pid + "\\";
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string visit_Path = path +"visit_" + visitNo + "_" + visitdate+"\\";
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
if (!IsVisitExist)
{
System.IO.Directory.CreateDirectory(path);
}
if (!IsVisitPath)
{
System.IO.Directory.CreateDirectory(visit_Path);\\error here
}
}
getting this value for visit_Path
C:\Users\Monika\Documents\Visual Studio 2010\Projects\SonoRepo\SonoRepo\bin\Debug\Patients\Patient_16\visit_4_16-10-2013 00:00:00\
You can not have : in directory name, I suggest you to use this to string to get date in directory name:
DateTime.Now.ToString("yyyy-MM-dd hh_mm_ss");
it will create timestamp like:
2013-10-17 05_41_05
additional note:
use Path.Combine to make full path, like:
var path = Path.Combine(strpath , "Patients", "Patient_" + pid);
and last
string suffix = "visit_"+visitNo+"_" + visitdate;
var visit_Path = Path.Combine(path, suffix);
In general always use Path.Combine to create paths:
String strPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = Path.Combine(strPath,"Patients","Patient_" + pid);
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string fileName = string.Format("visit_{0}_{1}", visitNo, visitdate);
string visit_Path = Path.Combine(path, fileName);
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
To replace invalid characters from a filename you could use this loop:
string invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalidChars)
{
visit_Path = visit_Path.Replace(c.ToString(), ""); // or with "."
}
You can't have colons : in file paths
You can't use colons (:) in a path. You can for example Replace() them with dots (.).
Just wanted to add my two cents.
I assigned the path from a text box to string and also adding additional strings, but I forgot to add the .Text to the text box variable.
So instead of
strFinalPath = TextBox1.Text + strIntermediatePath + strFilename
I wrote
strFinalPath = TextBox1 + strIntermediatePath + strFilename
So the path became invalid because it contained invalid characters.
I was surprised that c# instead of rejecting the assignment because of type mismatch, assigned invalid value to the final string.
So look at the path assignment string closely.
My image URL is like this:
photo\myFolder\image.jpg
I want to change it so it looks like this:
photo\myFolder\image-resize.jpg
Is there any short way to do it?
This following code snippet changes the filename and leaves the path and the extenstion unchanged:
string path = #"photo\myFolder\image.jpg";
string newFileName = #"image-resize";
string dir = Path.GetDirectoryName(path);
string ext = Path.GetExtension(path);
path = Path.Combine(dir, newFileName + ext); // #"photo\myFolder\image-resize.jpg"
You can use Path.GetFileNameWithoutExtension method.
Returns the file name of the specified path string without the extension.
string path = #"photo\myFolder\image.jpg";
string file = Path.GetFileNameWithoutExtension(path);
string NewPath = path.Replace(file, file + "-resize");
Console.WriteLine(NewPath); //photo\myFolder\image-resize.jpg
Here is a DEMO.
This is what i use for file renaming
public static string AppendToFileName(string source, string appendValue)
{
return $"{Path.Combine(Path.GetDirectoryName(source), Path.GetFileNameWithoutExtension(source))}{appendValue}{Path.GetExtension(source)}";
}
I would use a method like this:
private static string GetFileNameAppendVariation(string fileName, string variation)
{
string finalPath = Path.GetDirectoryName(fileName);
string newfilename = String.Concat(Path.GetFileNameWithoutExtension(fileName), variation, Path.GetExtension(fileName));
return Path.Combine(finalPath, newfilename);
}
In this way:
string result = GetFileNameAppendVariation(#"photo\myFolder\image.jpg", "-resize");
Result: photo\myFolder\image-resize.jpg
Or the File.Move method:
System.IO.File.Move(#"photo\myFolder\image.jpg", #"photo\myFolder\image-resize.jpg");
BTW: \ is a relative Path and / a web Path, keep that in mind.
You can try this
string fileName = #"photo\myFolder\image.jpg";
string newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) +
"-resize" + fileName.Substring(fileName.LastIndexOf('.'));
File.Copy(fileName, newFileName);
File.Delete(fileName);
try this
File.Copy(Server.MapPath("~/") +"photo/myFolder/image.jpg",Server.MapPath("~/") +"photo/myFolder/image-resize.jpg",true);
File.Delete(Server.MapPath("~/") + "photo/myFolder/image.jpg");
I am trying to take file names that look like:
MAX_1.01.01.03.pdf look like Max_1010103.pdf.
Currently I have this code:
public void Sanitizer(List<string> paths)
{
string regPattern = (#"[~#&!%+{}]+");
string replacement = " ";
Regex regExPattern = new Regex(regPattern);
Regex regExPattern2 = new Regex(#"\s{2,}");
Regex regExPattern3 = new Regex(#"\.(?=.*\.)");
string replace = "";
var filesCount = new Dictionary<string, int>();
dataGridView1.Rows.Clear();
try
{
foreach (string files2 in paths)
{
string filenameOnly = System.IO.Path.GetFileName(files2);
string pathOnly = System.IO.Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
sanitizedFileName = regExPattern2.Replace(sanitizedFileName, replacement);
string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);
if (!System.IO.File.Exists(sanitized))
{
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = filenameOnly;
clean.Cells[2].Value = sanitizedFileName;
dataGridView1.Rows.Add(clean);
System.IO.File.Move(files2, sanitized);
}
else
{
if (filesCount.ContainsKey(sanitized))
{
filesCount[sanitized]++;
}
else
{
filesCount.Add(sanitized, 1);
string newFileName = String.Format("{0}{1}{2}",
System.IO.Path.GetFileNameWithoutExtension(sanitized),
filesCount[sanitized].ToString(),
System.IO.Path.GetExtension(sanitized));
string newFilePath = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(sanitized), newFileName);
newFileName = regExPattern2.Replace(newFileName, replacement);
System.IO.File.Move(files2, newFilePath);
sanitized = newFileName;
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = filenameOnly;
clean.Cells[2].Value = newFileName;
dataGridView1.Rows.Add(clean);
}
//HERE IS WHERE I AM TRYING TO GET RID OF DOUBLE PERIODS//
if (regExPattern3.IsMatch(files2))
{
string filewithDoublePName = System.IO.Path.GetFileName(files2);
string doublepPath = System.IO.Path.GetDirectoryName(files2);
string name = System.IO.Path.GetFileNameWithoutExtension(files2);
string newName = name.Replace(".", "");
string filesDir = System.IO.Path.GetDirectoryName(files2);
string fileExt = System.IO.Path.GetExtension(files2);
string newPath = System.IO.Path.Combine(filesDir, newName+fileExt);
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value =doublepPath;
clean.Cells[1].Value = filewithDoublePName;
clean.Cells[2].Value = newName;
dataGridView1.Rows.Add(clean);
}
}
}
catch (Exception e)
{
throw;
//errors.Write(e);
}
}
I ran this and instead of getting rid of ALL period (minus the period before a file extension), I get results like: MAX_1.0103.pdf
If there are multiple periods like: Test....1.txt I get these results: Test...1.txt
It seems to only get rid of ONE period. I am pretty new to Regular Expressions and it is a REQUIREMENT for this project. Can anybody help me figure out what I'm doing wrong here?
Thanks!
EDITED to show changes made in code
Why not use the Path class:
string name = Path.GetFileNameWithoutExtension(yourPath);
string newName = name.Replace(".", "");
string newPath = Path.Combine(Path.GetDirectoryName(yourPath),
newName + Path.GetExtension(yourPath));
Each step separated for clarity.
So for the input
"C:\Users\Fred\MAX_1.01.01.03.pdf"
I get the output
"C:\Users\Fred\MAX_1010103.pdf"
which is what I'd expect.
If I supply:
"C:\Users\Fred.Flintstone\MAX_1.01.01.03.pdf"
I get:
"C:\Users\Fred.Flintstone\MAX_1010103.pdf"
again what I expect as I'm not processing the "DirectoryName" part of the path.
NOTE I missed the bit about RegEx being a REQUIREMENT. Still sticking by this answer though.
Say, didn't you already ask this question?
Anyway, I stick by my original answer:
string RemovePeriodsFromFilename(string fullPath)
{
string dir = Path.GetDirectoryName(fullPath);
string filename = Path.GetFileNameWithoutExtension(fullPath);
string sanitized = filename.Replace(".", string.Empty);
string ext = Path.GetExtension(fullPath);
return Path.Combine(dir, sanitized + ext);
}
Now, since you specified that you must use RegEx, I suppose you could always force it in there:
string RemovePeriodsFromFilename(string fullPath)
{
string dir = Path.GetDirectoryName(fullPath);
string filename = Path.GetFileNameWithoutExtension(fullPath);
// Look! Now the solution uses RegEx!
string sanitized = Regex.Replace(filename, #"\.", string.Empty);
string ext = Path.GetExtension(fullPath);
return Path.Combine(dir, sanitized + ext);
}
Note: This is basically the exact same approach that ChrisF suggested.
Whoever is requiring that you use RegEx, I suggest you request an explanation why.
I'd forgo regexes all together, do it like this:
Replace all periods with empty
strings
Replace the last 3
characters with ("."+Last 3
characters)
This regex will remove all periods except for the period before the 3 or 4 letter extension.
string filename = "test.test......t.test.pdf";
string newFilename = new Regex(#"\.(?!(\w{3,4}$))").Replace(filename, "");
If you want it to work with 2 letter extensions just change the {3,4} to {2,4}
Good luck!
Something like this, maybe:
string fileName = "MAX_1.01.01.03.pdf";
fileName = fileName.Substring(0, 1).ToUpper() + fileName.Substring(1).ToLower();
fileName = fileName.Replace(".", "");