Replace specific string in large string - c#

I'm writing a small WPF Application which helps my company to update costumer projects. I have a list of SQL-Files which I have to execute. Now these scripts are always written with a "USE [Insert_Database]". I read the whole content of a script into a string, but my Replace method doesn't seem to do anything.
string content = File.ReadAllText(file);
content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});

String.Replace returns the modified string, so it should be:
content = content.Replace(....);
This method does not modify the value of the current instance.
Instead, it returns a new string in which all occurrences of oldValue
are replaced by newValue.

You can use replace function as follow on strings
str = str.Replace("oldstr","newstr");
if oldstr is found in the str then it will be replaced by new str

You aren't using new value when you call replace.
string content = File.ReadAllText(file);
content = content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
for reference: the MSDN doc for replace https://msdn.microsoft.com/en-us/library/system.string.replace(v=vs.110).aspx

Related

How to get full path of file using File.WriteAllText in C#?

I have added key in settings file as <add key="Test.Directory" value="Data/Test/XML_Files" />.I need to pass this path to File.WriteAllText and concatenate as c:/Data/Test/XML_Files/TestFile but the path is taken only till c:/Data/Test/XML_Files.Please help to concatenate and get the full path
var xmlFilePath = ConfigurationManager.AppSettings["Test.Directory"];
string _xmlFileName = new DirectoryInfo(Path.GetFullPath(xmlFilePath));
string Records = string.Empty;
using (StringWriter Writer = new Utf8StringWriter())
{
xmlSerializer.Serialize(Writer, itemList);
Records = Writer.ToString();
}
File.WriteAllText(string.Format(#_xmlFileName + "'\'TestFile" + ".dat" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString().Substring(1, 5) ), Records);
You error seems to be in those quotes added around the backslash before the TestFile constant. But I strongly suggest you to be more clear in your building of the filename and to use Path.Combine to create the final full filename
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssfff") +
Guid.NewGuid().ToString().Substring(1, 5);
string file = Path.Combine(_xmlFileName, $"TestFile-{timestamp}.dat");
File.WriteAllText(file, Records);
Of course you could put everything in a single line, but this will not be a noticeable advantage of any kind for your performances and makes the understanding of the code really difficult. (Note, for example, that your original code has the datetime/guid part after the extension and this is probably an oversight caused by the complexity of the expression)
Maybe you can try something like this?:
var folderName = Path.Combine(#_xmlFileName, "TestFile");
var fileName = $#"{folderName}\{DateTime.Now:yyyyMMddHHmmssfff}.dat";
File.WriteAllText(fileName, txRrcWellRecords);

Remove Extra back slash "\" from string file path in c#

How to convert
"String path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
into
String path = #"C:\Abc\Omg\Why\Me\".
My approach is to first reverse the string and then remove all the "\" till we get first char, and the reverse it again.
How to do this in C#, is there any method for such operation?
You can just construct path using the Path static class:
string path = Path.GetFullPath(#"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\");
After this operation, variable path will contain the minimal version:
C:\Abc\Omg\Why\Me\
You can use path.TrimEnd('\\'). Have a look at the documentation for String.TrimEnd.
If you want the trailing slash, you can add it back easily.
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = path.TrimEnd('\\') + '\\';
another solution is
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = Path.GetFullPath(path);

The fastest way to trim string in C#

I need to trim paths in million strings like this:
C:\workspace\my_projects\my_app\src\my_component\my_file.cpp
to
src\my_component\my_file.cpp
I.e. remove absolute part of the path, what is the fastest way to do that?
My try using regex:
Regex.Replace(path, #"(.*?)\src", ""),
I wouldn't go with regex for this, use the plain old method.
If the path prefix is always the same:
const string partToRemove = #"C:\workspace\my_projects\my_app\";
if (path.StartsWith(partToRemove, StringComparison.OrdinalIgnoreCase))
path = path.Substring(partToRemove.Length);
If the prefix is variable, you can get the last index of \src\:
var startIndex = path.LastIndexOf(#"\src\", StringComparison.OrdinalIgnoreCase);
if (startIndex >= 0)
path = path.Substring(startIndex + 1);
define the regex with a new and reuse it
there is a (significant) cost to creating the regex
string input = "This is text with far too much " +
"whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
I'm not sure if you need speed here, but if you always get the full path, you could do a simple .Substring()
var path = #"C:\workspace\my_projects\my_app\src\my_component\my_file.cpp";
Console.WriteLine(path.Substring(32));
However, I think you should sanitize your input first; in this case, the Uri class could do the parsing step:
var root = #"C:\workspace\my_projects\my_app\";
var path = #"C:\workspace\my_projects\my_app\src\my_component\my_file.cpp";
var relative = new Uri(root).MakeRelativeUri(new Uri(path));
Console.WriteLine(relative.OriginalString.Replace("/", "\\"));
Notice here the Uri will change the \ with a /: that's the .Replace reason.
Cant think any faster than this
path.Substring(33);
What is before src is constant. and it starts from index 33.
C:\workspace\my_projects\my_app\src\my_component\my_file.cpp
^
How ever if its not always constant. you can find it once. and do the rest inside loop.
int startInd = path.IndexOf(#"\src\") + 1;
// Do this inside loop. 1 million times
path.Substring(startInd);
If your files will all end in "src/filename.ext" you could use the Path class in the .NET framework for it and get around all caveats you could have with pathes and filenames:
result = "src\" + Path.GetFileName(path);
So you should first double-check that the conversion is the thing that takes to long.

c# how to get one value from substring

How to solve this?
What i want to change this :
C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\
to new value:
value = "1.0.11";
You could just get the Name of the corresponding DirectoryInfo:
string path = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
string version = new DirectoryInfo(path).Name;
Alternative method:
var path = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
var value = Path.GetFileName(path.TrimEnd(new[]{'/','\\'}));
// OUTPUT: 1.0.1.1
This basically removes any last directory delimeters and then treats the last directory as a filename, so it returns the last directory.
Based on #JeppeStigNielsen's comments below, here's a better, platform independent alternative.
var value = Path.GetFileName(Path.GetDirectoryName(path));
This will work if there is a file name present as well.
var value = Path.GetFileName(Path.GetDirectoryName(".../1.0.1.1/somefile.etc"));
// returns 1.0.1.1
Darin's answer is great but as an alternative;
string s = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
string[] array = s.Split('\\');
Console.WriteLine(array[array.Length - 2]);
Output will be;
1.0.1.1
Here a DEMO.

Inserting on file path

Right now I have files being output to a path; "C:\Users\Daniel\Average.txt"
I'm trying to write a function to input the current timestamp after the "Average" but before the .txt
I know this is pretty elementary, but I don't know where to begin...
EDIT: I originally had it hardcoded;
string path = "C:\Users\Daniel\Average.txt";
You can just use this instead:
var outputFile = #"C:\Users\Daniel\Average.txt";
var outputDir = Path.GetDirectoryName(outputFile);
var fileWithTimeStamp = string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(outputFile),
DateTime.Now.ToString("yyyyMMddHHmmssffff"),
Path.GetExtension(outputFile));
var outputWithTimeStamp = Path.Combine(outputDir, fileWithTimeStamp);
My Test with LINQPad:
outputWithTimeStamp.Dump();
C:\Users\Daniel\Average_201304230828184465.txt
You can use Path.GetFileNameWithoutExtension.
var info=new FileInfo(#"C:\Users\Daniel\Average.txt");
var span=TimeSpan.FromTicks(DateTime.Now.Ticks).ToString();
var name=Path.GetFileNameWithoutExtension(info.FullName);
name=(new[] { name, span, info.Extension }).Aggregate(String.Concat);
The name is what you want finally.
There's another way to composite with a full name:
var info=new FileInfo(#"C:\Users\Daniel\Average.txt");
var span=TimeSpan.FromTicks(DateTime.Now.Ticks).ToString();
var fullName=info.FullName;
var length=fullName.LastIndexOf(info.Extension);
fullName=fullName.Substring(0, length);
fullName=(new[] { fullName, span, info.Extension }).Aggregate(String.Concat);
I think something like this will work for you:
StreamWriter sw = new StreamWriter("C:\Users\Daniel\Average"+DateTime.Now.ToString(ADD_FORMAT_HERE) +".txt");
Then you will need to dump the contents into the file.
Try string.format:
string Today = DateTime.Now.ToString("MMMM_dd");
string name = string.Format(#"Average_{0}.txt",Today);
You can alter the DateTime.Now.ToString( to include seconds, minutes etc...
//have a string variable which holds your output
String output;
File.WriteAllText("C:\Users\Daniel\Average" + DateTime.Now + ".txt",output);
this will create the text file and writes the output to that file.

Categories