Question

I'm taking pdf file names in telerik sitefinity like this :

test..pdf (41 KB )

1..pdf (34 KB )

How to change these like this? test.pdf and 1.pdf

Was it helpful?

Solution 2

If the extension is un-known, so in your case it's PDF, this simply can be done by:

string fileName = string.Format("{0}.pdf","test..pdf (41 KB )".Split('.')[0]);

if you need more flexibility, can make PDF as string variable too.

Do not simply replace, as the file can contain points too.

OTHER TIPS

If they all look like this (two periods instead of one you could simply do:

myFileName = myFileName.Replace("..", ".");

Also it seems I didn't consider the size of the file that is appended to the path. That can be removed by splitting on the space, and taking the first element like this:

myFileName = myFileName.Split(' ')[0];

To obtain both the replacement of .. with . and remove the filesize, you can just chain them both together like this:

myFileName = myFileName.Replace("..", ".").Split(' ')[0];

The String.Replace method would allow you to replace ".." with "." as long as you know there are no other cases where you may want ".."

EG:

 pdfFile = pdfFile.Replace("..", ".");

simpler: string fileName = tempFileName.Replace("..pdf",".pdf");

For performance, use StringBuilder.Replace() method,

StringBuilder strBuilder = new StringBuilder(tempFileName);
strBuilder.Replace("..pdf", ".pdf");
string fileName = strBuilder.ToString();

And if you're like me who only would want one instance replaced(this is slightly tricky)

string ReverseString(string p)
{
    char[] arr = p.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}

var regex = new RegEx("fdp..");
var fileName = ReverseString(regex.Replace(ReverseString(tempFileName), "fdp.",1));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top