Why does my fileName equals with something like "29.06.2014 17:04:23.pdf" ?
string dateTime = DateTime.Now.ToString();
string fileName = dateTime.Trim() + ".pdf";
I don't understand why there is a space between date and time. Even
string fileName = Datetime.Now.Date.ToString() + Datetime.Now.Hour.ToString() + ".pdf";
doesn't work.
You should use String.Replace method
string dateTimeStr = DateTime.Now.ToString();
string fileName = String.Format("{0}.pdf"
dateTimeStr.Replace(" ", String.Empty));
Because String.Trim method deals only with whitespaces at the beginning and the end of the string
Related
I need to insert in a specific position of the string line, another string, so I compute the specific position for start to insert:
string info1 = "info1";
string info2 = "info2";
string info3 = "info3";
string info4 = "info4";
string keyWord = "BELEGIT";
start = line.IndexOf(keyWord, 0) + keyWord.Length + 13;
var aStringBuilder = new StringBuilder(line);
aStringBuilder.Remove(start, 19);
line = aStringBuilder.ToString();
string newLine = line.Insert(start, "\r\n" + info1 + "\r\n" + "\r\n" + info2 + "\r\n" + info3 + "\r\n" + info4 + "\r\n");
(newLine will be the content of a file in my application).
newline contains the correct content except the string "00000" that inserts after "info4". So in my new file with the content that is newline there is newline and immediately after "00000". I do not really understand why.
Thanks in advance.
INPUT:
line contains:
#~11\r\nT-02040121R\r\n\r\n\r\n\r\n\r\n\r\n\n2.000000000\r\n
OUTPUT
newLine contains:
#~11\r\nT-02040121R\r\ninfo1\r\n\r\ninfo2\r\ninfo3\r\ninfo4\r\n00000\r\n
Assuming that you want just the first 19 chars of lineyou could use Substringto get them and string.Formatto build the new string.
Something like this
var start = line.Substring(0, 19);
string newLine = $"{start}\r\n{info1}\r\n\r\n{info2}\r\n{info3}\r\n{info4}\r\n";
The second line is the short form for
string newLine = string.Format("{0}\r\n{1}\r\n\r\n{2}\r\n{3}\r\n{4}\r\n", start, info1, info2, info3, info4);
if you need more information about string.Formathave a look at the MSDN.
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.
Here is what I have tried, please note that lblImageAlt.Text property has been set to 'Images/'
string ImgPath1 = lblImageAlt1.Text.ToString();
string ImgPath2 = lblImageAlt2.Text.ToString();
string ImgPath3 = lblImageAlt3.Text.ToString();
string filename1 = "";
string filename2 = "";
string filename3 = "";
if (fileuploadimages1.HasFile)
{
if (File.Exists(Server.MapPath(ImgPath1 + filename1)))
{
string extension = Path.GetExtension(filename1);
string name = Path.GetFileNameWithoutExtension(filename1);
int fileMatchCount = 1;
while (File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
fileMatchCount++;
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
}
else
{
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));
}
}
else
{
filename1 = "noImage.jpg";
}
but the same image does not get a number appended to it. What am I doing wrong here?
Path.GetFileName returns the whole filename with the extension.
Thus your code is checking if a file exists with a name like this:
image.jpg1
You should change the code to split the filename in two parts, the base filename and the extension, then check if the filename exists and then rebuild the filename from its parts adding the increment number until you find a non existant filename
// Extract just the filename from the posted file removing the path part (image.jpg)
filename1 = Path.GetFileName(fileuploadimages1.PostedFile.FileName);
baseFile = Path.GetFileNameWithoutExtension(fileuploadimages1.PostedFile.FileName);
extension = Path.GetExtension(fileuploadimages1.PostedFile.FileName);
int fileMatchCount = 1;
// Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
while(File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1)))
{
// The given file exists already, so we now need to build
// a different (but related) filename using a counter....
// This will create a filename like 'image(001).jpg'
// and then we will restart the loop
fileName1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
// ... but first increment the counter in case even the new name exists
fileMatchCount++;
}
// We exit the loop with a name that should not exists in the destination folder
fileuploadimages1.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1));
You're not actually modifying filename1. You're checking if it ends in a (0), (1), etc. and incrementing your index, but never actually modifying the variable.
Try using
if(File.Exists(Server.MapPath(ImgPath1 + filename1)))
{
string extension = Path.GetExtension(filename1);
string name = Path.GetFileNameWithoutExtension(filename1);
int fileMatchCount = 1;
while(File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
fileMatchCount++;
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
}
else
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));