trim a string in c# - c#

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

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];

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.

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));

Related

Write Tab Delimited File

I'm having trouble writing a Tab-delimited File and I've checked around here and have not gotten my answers yet.
So I've got a function that returns the string with the important pieces below (delimiter used and how I build each line):
var delimiter = #"\t";
sb.Append(string.Join(delimiter, itemContent));
sb.Append(Environment.NewLine);
The string returned is like this:
H\t13\t170000000000001\t20150630
D\t1050\t10.0000\tY
D\t1050\t5.0000\tN
And then I write it to a file with this (content below is the string above):
var content = BuildFile(item);
var filePath = tempDirectory + fileName;
// Create the File
using (FileStream fs = File.Create(filePath))
{
Byte[] info = new UTF8Encoding(true).GetBytes(content);
fs.Write(info, 0, info.Length);
}
However, the file output is this with no tabs (opened in notepad++):
H\t13\t170000000000005\t20150630
D\t1050\t20.0000\tN
D\t1050\t2.5000\tY
When it should be more like this (sample file provided):
H 100115980 300010000000003 20150625
D 430181 1 N
D 342130 2 N
D 459961 1 N
Could this be caused by the encoding I used? Appreciate any input you may have, thanks!
Using var delimiter = #"\t";, the variable contains a literal \ plus t. The # syntax disables the backslash as "special". In this case you really want
var delimiter = "\t";
to have a tab character.
There is a typo in your code. The # prefix means that the following string is a literal so #"\t" is a two-character string with the characters \ and t
You should use "\t" without the prefix.
You should consider using a StreamWriter instead of constructing the entire string in memory and writing the raw bytes though. StreamWriter uses UTF-8 by default and allows you to write formatted lines just as you would with Console.WriteLine:
var delimiter ="\t";
using(var writer=new StreamWriter(filePath))
{
var line=string.Join(delimiter, itemContent);
writer.WriteLine(line);
}

Taking the last Substring of a string in C#

I have a string
"\uploads\test1\test2.file"
What's the method to get just "test2.file"?
What I have in my mind is to get the last index of "\" and then perform a string.substring(last index of "\") command on it?
Is there a method that takes just the word after the last "\"?
Use the method Path.GetFileName(path); in System.IO namespace, it is much more elegant than doing string operations.
You could use LINQ:
var path = #"\uploads\test1\test2.file";
var file = path.Split('\\').Last();
You might want to validate the input, if you're concerned about path potentially being null or whatnot.
You could do something like this:
string path = "c:\\inetpub\\wwwrroot\\images\\pdf\\admission.pdf";
string folder = path.Substring(0,path.LastIndexOf(("\\")));
// this should be "c:\inetpub\wwwrroot\images\pdf"
var fileName = path.Substring(path.LastIndexOf(("\\"))+1);
// this should be admin.pdf
For more take a look at here How do I get the last part of this filepath?
Hope it helps!
You can use the Split method:
string myString = "\uploads\test1\test2.file";
string[] words = myString.Split("\");
//And take the last element:
var file = words[words.lenght-1];
using linq:
"\uploads\test1\test2.file".Split('\\').Last();
or you can do it without linq:
string[] parts = "\uploads\test1\test2.file".Split('\\');
last_part=parts[parts.length-1]

How can I replace the same name of a file using regex but in another format?

I am new in programming and not so good about regex. I wish to load / read a csv File and then save in a txt File using the same name of csv File. I will give an example.
D:\Project\File\xxx.csv
After I load this file, I want to get the name "xxx" and save it in a txt file:
D:\Project\File\xxx.txt
Or maybe in another folder, for example:
D:\Project\Specifications\PersonInfo.csv
save to
D:\Project\DataBank\PersonInfo.txt
This can be accomplished in many ways.
Maybe what you're lacking is knowledge of the System.IO.Path class (MSDN article here).
For instance changing the extension could be accomplished like so:
string originalFilePath = #"D:\Project\File\xxx.csv";
string newFilePath = Path.ChangeExtension(originalFilePath, ".txt");
Note: You need to explicitate the leading dot (".") for the extension.
Here's some "Path algebra" fun you could combine to create your desired effects:
string originalFilePath = #"D:\Project\File\xxx.csv";
string thePath = Path.GetDirectoryName(originalFilePath);
// will be #"D:\Project\File"
string filename = Path.GetFileName(originalFilePath);
// will be "xxx.csv"
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(originalFilePath);
// will be "xxx"
string recombinedFilePath = Path.Combine( #"D:\OtherFolder", "somethingElse.txt" );
// will be #"D:\OtherFolder\somethingElse.txt"
Note: Path.Combine knows how to handle extra/missing leading/trailing backslashes.
For example:
Path.Combine(#"D:\MyFolder1", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1", #"\MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"\MyFolder2\MyFile.txt")
will all yield the same result: #"D:\MyFolder1\MyFolder2\MyFile.txt"
You do not need regex for that, because .NET provides a System.IO.Path class for dealing specifically with file name manipulations.
For example, to replace .csv with .txt you can use this call:
var csvPath = #"D:\Project\File\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(csvPath)
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You use a similar trick to replace other parts of the file path. Here is how you change the name of the top directory:
var csvPath = #"D:\Project\Specifications\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(Path.GetDirectoryName(csvPath))
, "DataBank"
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You don't need Regex.
You can use Path.GetFileName or Path.GetFileNameWithoutExtension:
string fileName = Path.GetFileNameWithoutExtension("D:\Project\Specifications\PersonInfo.csv");
If you want to use regex for this, this regex will get the part you want:
([^\\]+)\.[^.\\]+$
The first group (in the parentheses) matches one or more characters (as many as possible) which is not a backslash. Then there need to be a literal dot. Then one or more characters (as many as possible) that are not a dot or backslash, then the end of the string. The group captures the wanted part.

Writing to a text file with a variable for the name

Alright, so my question is; I'm trying to save a file to the C: drive in a folder. Now, I know how to do this for regular files like
using(StreamWriter writer = new SteamWriter("c:\\Folder\\TextFile.txt");
What I've been trying to figure out is how I can make it so that the name of text file is the replaced with a variable so Its more like
using(StreamWriter writer = new SteamWriter("c:\\Folder\\Variablegoeshere.txt");
Is there anyway I can do this?
I apologize for my poor question asking skills.
The StreamWriter constructor, like many other constructors and method calls, takes a string argument. You can pass it any string you like. In your first code sample, you're passing the constructor a "string literal" - an unnamed string variable with a constant value. Instead, you can pass a standard string variable, that you construct beforehand. For instance:
string name = // whatever you like
string path = "c:\\Folder\\" + name + ".txt"; // use '+' to combine strings
using (StreamWriter writer = new SteamWriter(path));
I usually like to use the Path.Combine static method when I concatenate path components. Helps me avoid problems with missing or doubled backslashes:
string path = System.IO.Path.Combine("c:\\Folder", name + ".txt");
And, finally, with the string verbatim modifier, you avoid those ugly double-backslashes, that are otherwise necessary because the backslash is the "escape" character in non-verbatim strings:
string path = System.IO.Path.Combine(#"c:\Folder", name + ".txt");
Here's the Microsoft developer reference page for strings in C#. Worth a read, as is the larger C# language reference.
var inputPath = "c:\\Folder\\TextFile.txt";
var folderPath = Path.GetDirectoryName( inputPath );
using ( var writer = new StreamWriter ( Path.Combine( folderPath, "Variablegoeshere.txt" ) )

How to remove characters in a string?

How to remove the some characters in a string ..
string s="testpage\information.xml"
I need only information.xml how to do that?
System.IO.Path may help you with this since the string contains a file path information. In your case, you may use Path.GetFileName(string path) to get the file name from a string.
Example
string s = #"testpage\information.xml";
string filename = Path.GetFileName(s);
//MessageBox.Show(filename);
Thanks,
I hope you find this helpful :)
Assuming the value that will be in s is always a file path, use the Path class to extract the file name
var filename = Path.GetFileName(s);
File path is of the form
aaaa\bbb\ccc\dddd\information.xml
To retrieve the last string, you can divide your string using the delimiter \
String path = #"aaaa\bbb\ccc\dddd\information.xml";
String a[] = path.Split('\\');
This will give String array as ["aaaa", "bbb", "ccc", "dddd", "information.xml"]
You can retrieve the filename as
String filename = a[a.Length-1];
If it is going to be a file path, then you can use the System.IO.Path class (MSDN) to extract the filename.
string s = "testpage\information.xml"
var filename = Path.GetFilename(s);
If it's always right of the backslash separator then you can use:
if (s.Contains(#"\"))
s= s.Substring(s.IndexOf(#"\") + 1);
Hope this is what you want:
var result=s.Substring(s.LastIndexOf(#"\") + 1);
If you are using file paths, see the Path.GetFileName Method
It will not check whether the file exists or not. So it will be faster.
s = Path.GetFileName(s);
If you need to check whether file exists, use File.Exists class.
Another way is to use String.Split() method
string[] arr = s.Split('\\');
if(arr.Length > 0)
{
s = arr[arr.Length - 1];
}
Another way is to use RegEx
s = Regex.Match(s, #"[^\\]*$").Value;
You can use the following line of codes to get file extension.
string filePath = #"D:\Test\information.xml";
string extention = Path.GetExtension(filePath);
If you need file name alone use,
string filePath = #"D:\Test\information.xml";
string filename = Path.GetFilename(filePath );
Use string.Replcae
string s = #"testpage\information.xml";
s = s.Replace(#"testpage\\",""); // replace 'testpage\' with empty string
You will get Output => s=information.xml
# is need only because you have backslash in your string
For further reading about STRING REPLACE
http://www.dotnetperls.com/replace
http://msdn.microsoft.com/en-us/library/system.string.replace.aspx
In C++ you can do something like this. Basically search for "/" or "\" from right to left of the path and crop the string starting from the first occurance of the delimiter:
string ExtractFileName(const string& strPathFileName)
{
size_t npos;
string strOutput = strPathFileName;
if(strPathFileName.rfind(L'/', npos) || strPathFileName.rfind(L'\\', npos))
{
strOutput = strPathFileName.substr(npos+1);
}
return strOutput;
}

Categories

Resources