Remove some text from a filename on save - c#

Ok what I am doing is selecting a file name and saving the filename only. What I need to do is remove certain text from it but it changes and that's the issue I am having.
The main one is it has name_zm and I want to remove _zm from the name.
But some other files have ak47_fmg_mp and all i want is the first before the _
but not sure how to accomplish this.
I have tried text replace regex even but none of it has worked
string result = nyu_res.filename;
result = result.Replace("_zm", "");
Well when i select a file it saves the filename in this example. Lets say I selected
m14_zm
What I want to do is get m14 and thats it. Same with the others. Just want to get to the first '_'. I tried the code above but could not get it to work.
Any help would be much appreciated.

Use Split('_') and take the first one.
Then you don't have to check if it contains _ or not.
result = result.Split('_')[0];

Check your string for Null/Empty and '_' then you can use Substring and IndexOf to do that :
var result = "fileName_zm";
if(!string.IsNullOrEmpty(result) && result.Contains('_'))
{
result = result.Substring(0, result.IndexOf("_"));
}
Advantage: if string is Null/Empty it will short circuit and you will save few cycles of CPU.

Related

Delete specific row from File

I have this little project in C# where I am manipulating with files. Now my task is that I have to delete specific rows from files.
For example my file looks like this:
1-this is the first line
2-this is the second line
3-this is the third line
4-this is the fourth line
Now how can I keep only the first two rows and delete only the last two rows?
Note- this is how I read the file from my local machine:
string[] lines = File.ReadAllLines(#"C:\Users\admin\Desktop\COMMANDS.dat");
I have tried something like this but I think it's not so "efficient"
string text = File.ReadAllText(#"C:\Users\admin\Desktop\COMMANDS.dat");
text = text.Replace(lines[2], "");
text = text.Replace(lines[3], "");
File.WriteAllText(#"C:\Users\admin\Desktop\COMMANDS.dat", text);
So this actually does the job, it replaces the lines by string with an empty character but when I take a look at the file, I don't want to have 4 lines there, even though 2 of them are real strings and the other two are just empty lines... Can I manage to do this in another way?
Try replacing the newline character with an empty string:
string text = File.ReadAllText(#"C:\Users\admin\Desktop\COMMANDS.dat");
text = text.Replace(lines[2], "").Remove(Environment.NewLine, "");
text = text.Replace(lines[3], "").Remove(Environment.NewLine , "");
File.WriteAllText(#"C:\Users\admin\Desktop\COMMANDS.dat", text);
If my answer is useful, please mark it as accepted, and upvote it.
async Task Example()
{
var inputLines = await File.ReadAllLinesAsync("path/to/file.txt");
var outputLines = inputLines.Where((l, i) => i < 2);
await File.WriteAllLinesAsync("target/file.txt", outputLines);
}
What it does
Read data but not as one string but as a collection of lines
Create a new collection containing only the lines you want in your output
Write the filtered lines
Notes:
This example is not optimized for memory usage (because we read all lines and for larger files, e.g. multiple GB, this will fail). See existing answers for memory optimized version) - but: It's totally fine to do it this way if you know you have just a few k lines. (and it's faster)
Try not to "modify" strings. This will always create a copy and needs a lot of memory.
In this "Linq style" (functional) approach, we should treat data as immutable. That means: we have one variable that represents the input file and one variable that represents the result. We use declarative Linq to describe how the output should look like. "output is input where the filter index < 2 matches" instead of "if xy remove line" in an imperative style.

Get partcular information from text file (C#)

I need a c# program which can split strings and copy some particular informations into another file.
I've a text file like this:
BRIDGE.V2014R6I1.SOFT
icem.V4R12I2.SOFT
mygale.V4R1I1.SOFT,patch01_MAJ_APL.exe
photoshop.V2014R10I1.SOFT
rhino.V5R0I1.SOFT,patch01_Update_Files.exe
TSFX.V2R3I2.SOFT,patch01_corrections.exe,patch02_clock.exe,patch03_correction_tri_date.exe,patch04_gestion_chemins_unc.exe
and I need only some of these information into another file as below :
BRIDGE,SOFT
ICEM,SOFT
MYGALE,SOFT
PHOTOSHOP,SOFT
any helps pls :)
As I don't know, wether your text file is always like that, I can only provide a specific answer. First of all you have to, as ThatsEli pointed out, split the string at the point:
var splitted = inputString.Split(".");
Now it seems as though your second (zero based index) item has the irrelevant information with a comma splitted from the relevant. So all you have to do is to build together the zeroth and the second, while the second only has the first part before the comma:
var res = $"{splitted[0]},{splitted[2].Split(",")[0]}";
However, you seem to want your result in uppercase:
var resUpper = res.ToUpper();
But actually this only works as long as you have a perfect input file - otherwise you have to check, wether it actually has that many items or you'll get an IndexOutOfRange exception.
Actually I'm not sure wether you know how to read/write from/to a file, so I'll provide examples on this as well.
Read
var path = #"Your\Path\To\The\Input\File";
if (!File.Exists(path))
{
Console.WriteLine("File doesn't exist! If you're using a console, otherwise use another way to print error messages");
return;
}
var inputString = File.ReadAllText(path);
Write
var outputPath = #"your\Output\Path";
if(!File.Exists(outputPath))
{
Console.WriteLine("You know what to put here");
return;
}
File.WriteAllText(outputPath, inputString);
I would split the string and create a new file with parts of the array you got from the split.
You can split a string with eg. Split(".");
And then e.g. create a new string stringname = splitstring[0] + "," + splitstring[2]
That would add the first and third part back together.
That would apply to your first line.

Can't clear the white spaces with the most common methods

This is the case - I need to work with the Text property of a ToolStripItem and I need to clear all white spaces from the string before that. However I tried three very common (in my opinion) scenarios and neither of them returned a string with no white spaces. Here is what I tried:
string tempBtnText = tempItem.Text;
tempBtnText is defined inside the method where I work with the Text property. I find it easier this way. Then I tried those:
tempBtnText.Replace(" ", String.Empty);
tempBtnText = Regex.Replace(tempItem.Text, #"^\s*$\n", string.Empty);
string tempBtnTexts = Regex.Replace(tempItem.Text, #"\s+", "");
All those returned the string in it's original form (with white spaces). The only way to remove the white spaces was by using this method :
public string RemoveWhitespace(string input)
{
return new string(input.ToCharArray()
.Where(c => !Char.IsWhiteSpace(c))
.ToArray());
}
Which I found in a similar post here in SO. but I really don't understand why all of the above approaches don't work. I'm starting to think that there is something to do with the fact that I'm using a ToolStripItem Text property but as shown at the very begining I declare my own string variable that takes the value of the Text property and.
I don't know. Can someone tell me, what is the reason of this behavior. Not that it's that big of a problem to use another method for clearing the white spaces but the not working options are much more compact and readable and I would like to use one of them if possible.
Strings are immutable, what means that any operation produces a new instance, so you need assign any method result back to input:
string input = "...";
intput = intput.Replace(x, y);
You are not assigning the result back to tempBtnText
tempBtnText.Replace(" ", String.Empty);
it should be:
tempBtnText = tempBtnText.Replace(" ", String.Empty);
strings are immutable, string.Replace returns a new string, it doesn't modify the existing one.
abatischev is right so writing
tempBtnText = tempBtnText.Replace(" ", String.Empty);
should solve your problems. If you only want to remove Whitespaces in front and back then rather use:
tempBtnText = tempBtnText.Trim();

about string removing in C#

Whats is correct to do?
check if exists, then remove?
var input = "foo #main baa";
if(input.Contains("#main")) {
input = input.Replace("#main", "");
}
or just:
input = input.Replace("#main", "");
Well, this seem a simple question,but I really want know.
Thanks in advance.
The Contains check actually just makes your code slower.
Remove it.
The Contains call needs to loop through the string until it finds #main.
The Replace call then needs to do the same exact loop (it can't remember it from the Contains call).
This is a Shlemiel the Painter's algorithm.
Replace can handle strings with zero or more occurrences of the search string, so you don't need the check.
Just do the replacement - if it's not there, nothing should happen.
Just make the call to Replace(). If the substring isn't found nothing happens and you avoid an additional call to Contains().
I would do this:
input = input.Replace("#main", "").Replace(" "," ");
To remove any double spaces.
Just remove it. The only thing to check is if the string is null or not.

C# - Check filename ends with certain word

Hi I would like to know how to validate a filename in C# to check that it ends with a certain word (not just contains but is located at the end of the filename)
e.g I want to modify certain files that end with the suffix Supplier so I want to validate each file to test if it ends with Supplier, so LondonSupplier.txt, ManchesterSupplier.txt and BirminghamSupplier.txt would all be validated and return true but ManchesterSuppliers.txt wouldn't.
is this even possible? I know you can validate a filename to test for a certain word anywhere within a filename but is it possible to do what i'm suggesting?
Try:
Path.GetFileNameWithoutExtension(path).EndsWith("Supplier")
if (myFileName.EndsWith("whatever"))
{
// Do stuff
}
By utilizing the System.IO.Path.GetFileNameWithoutExtension(string) method, you can extract the filename (sans extension) from a string. For example, calling it with the string C:\svn\trunk\MySourceFile.cs would return the string MySourceFile. After this, you can use the String.EndsWith method to see if your filename matches your criteria.
Linq solution:
var result = FilePaths.Where(name => Path.GetFileNameWithoutExtension(name).EndsWith("Supplier"))
.Select(name => name).ToList();
Assuming that FilePaths is a list containing all the paths.

Categories

Resources