I'm currently trying to add a DateTime stamp, a prefix and a unique number to a file name. My desired output is:
\ParentDirectory\Sub Directory\Another Sub Directory\Prefix- Unique Number - 11 29 2016 2 07 30 PM.xlsx
Prefix and Unique Number above will be passed into the function. I'm using the following method to achieve this:
public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber)
{
return string.Concat(
Path.GetFullPath(fileName),
Path.Combine(prefix + " - " + uniqueNumber + " - "),
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString()
.Replace("/", " ")
.Replace(":", " ")
.Trim(),
Path.GetExtension(fileName)
);
}
I call the above method as:
string fileName = #"\\ParentDirectory\Sub Directory\Another Sub Directory\MyFile.xlsx";
string adjustedFileName = fileName.AppendDateTimeToFileName("Shipping Note", "0254900");
The output I receive is as follows:
\ParentDirectory\Sub Directory\Another Sub Directory\Shipping Note -\0254900 - 11 29 2016 2 08 10 PM
As you can see in the above output the string is incorrect, firstly I get an extra -\ and the file extension isn't coming through either. Can someone tell me where I'm going wrong please.
Here's how I'd do it
public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber)
{
return Path.Combine(
Path.GetDirectoryName(fileName),
string.Concat(
prefix,
" - ",
uniqueNumber,
" - ",
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString("MM dd yyyy h mm ss tt"),
Path.GetExtension(fileName)));
}
This correctly uses Path.Combine to combine the directory from Path.GetDirectoryName and you're new concatenated file name. Note I also used a date format string instead of the replacements. You might want to consider changing that format and putting a separator between the file name and the date.
The posted version of your code give the following output:
\ParentDirectory\Sub Directory\Another Sub Directory\MyFile.xlsxShipping Note - 0254900 - MyFile29 11 2016 15 46 48.xlsx
and NOT as you posted:
\ParentDirectory\Sub Directory\Another Sub Directory\Shipping Note -\0254900 - 11 29 2016 2 08 10 PM
if your desired output is:
\ParentDirectory\Sub Directory\Another Sub Directory\Prefix- Unique Number - 11 29 2016 2 07 30 PM.xlsx
You need to move the directory into the Path.Combine and use GetDirectoryName. Also remove the line:
Path.GetFileNameWithoutExtension(fileName)
since in your desired output I don't see the old file name "MyFile".
This code:
public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber)
{
return string.Concat(
Path.Combine(Path.GetDirectoryName(fileName), prefix + " - " + uniqueNumber + " - "),
DateTime.Now.ToString()
.Replace(".", " ")
.Replace(":", " ")
.Trim(),
Path.GetExtension(fileName)
);
}
will yield the following output:
\ParentDirectory\Sub Directory\Another Sub Directory\Shipping Note - 0254900 - 29 11 2016 15 39 37.xlsx
Related
So I'm currently trying to remove the following chars: "# " (With the space) It kinda works, because I have 3 lines, and it removes it on the first line. Here is my code:
string serverInfo = "Connected to 74.91.119.188:27015\n" +
"hostname:[FN] 24 / 7 Surf Utopia | Styles | !KNIFE,!WS,!GLOVES\n" +
"version: 1.37.9.5 secure\n" +
"os : Linux\n" +
"type : community dedicated\n" +
"map: surf_utopia_v3\n" +
"players : 24 humans, 0 bots(64 / 0 max)(not hibernating)\n" +
"# userid name uniqueid connected ping loss state rate\n" +
"# 3785 1 \"Con\" STEAM_1:0:128083116 03:13 32 0 active 196608\n" +
"# 3786 2 \"yolo\" STEAM_1:0:172863146 03:13 171 0 active 196608\n" +
"# 3787 3 \"chodyツ\" STEAM_1:0:42129452 03:13 46 0 active 786432\n" +
"#end\n";
var removeEnd = serverInfo.IndexOf("#end");
var newString = serverInfo.Remove(removeEnd);
var firstHashTag = newString.IndexOf("#");
var secondHashTag = newString.IndexOf("#", firstHashTag + 1);
var final = newString.Substring(secondHashTag);
if (final.Contains("# "))
{
var index = final.IndexOf("# ");
var newFinal = final.Substring(index + 2);
Console.WriteLine(newFinal);
}
Console.ReadLine();
Here is the output:
My question is:
How can I apply this to every line, I don't know how many lines there will be, all I know is that I need to remove "# " from every line there might be. (I don't know how many there will be, this is just for practice)
So you want to remove all occurrences of "# "? Why don't you just use
string newString = serverInfo.Replace("# ","");
This outputs:
Connected to 74.91.119.188:27015
hostname:[FN] 24 / 7 Surf Utopia | Styles | !KNIFE,!WS,!GLOVES
version: 1.37.9.5 secure
os : Linux
type : community dedicated
map: surf_utopia_v3
players : 24 humans, 0 bots(64 / 0 max)(not hibernating)
userid name uniqueid connected ping loss state rate
3785 1 "Con" STEAM_1:0:128083116 03:13 32 0 active 196608
3786 2 "yolo" STEAM_1:0:172863146 03:13 171 0 active 196608
3787 3 "chodyツ" STEAM_1:0:42129452 03:13 46 0 active 786432
#end
If you want to do something on a string line by line you should use System.IO.StringReader class:
using (StringReader reader = new StringReader(yourMultiLineString)
{
while((line = reader.ReadLine()) != null){
string line = reader.ReadLine();
//do something on line here
}
}
That's it, I left the implementation code to you.
Here is the code solution for your problem. Keep looping and removing until the index of remove string is -1. Keep in mind that the function "Replace" works on the first value it finds.
var textToRemove = "#end";
while(serverInfo.IndexOf(textToRemove) > -1)
{
serverInfo = serverInfo.Replace(textToRemove, string.Empty);
}
Why does this snippet of code
string str = 30 + 20 + 10 + "ddd";
Console.WriteLine(str);
produces 60ddd,
and this one
string str = "ddd" + 30 + 20 + 10;
Console.WriteLine(str);
produces ddd302010?
Seems like it's very simple, but I can't get my head around it.
Please, show me direction in which I can go in order to find a detailed answer.
Thanks!
The + operators in the expression you show have equal precedence because they're the same operator, hence are evaluated left to right:
30 + 20 + 10 + "ddd"
-- + (int, int) returns (int)50
------- + (int, int) returns (int)60
------------ + (object, string) returns (string)"60ddd"
Then for the other case:
"ddd" + 30 + 20 + 10
----- + (string, object) returns (string)"ddd30"
---------- + (string, object) returns (string)"ddd3020"
--------------- + (string, object) returns (string)"ddd302010"
It's because an expression is evaluated from left side to right side. In the first example 30 + 20 + 10 gives you int + string (30 + 20 + 10) - int, "ddd" - string. In the second example "ddd" + 30 is a string "ddd30" that appends "20" and "10" to it. It's all about the order (unless you have paranthesis).
It's evaluated from left to right. The first example has the numbers first, so it starts by evaluating as numbers. Then it finds out it has to evaluate as string. The second example is the other way around. It starts with string and continues with string.
Operator + has different overloads:
int + int = int
int + string = string
string + int = string
In Following Expression:
string str = 30 + 20 + 10 + "ddd";
Console.WriteLine(str);
First 30 + 20 got evaluates both are integers so output of operator will be integer which is 50.
Then 50 + 10 will be evaluated which both are again integers so integer will be output which is 60.
Then 60 + "ddd" which is integer + string operation the operator in this case output string so 60 + "ddd" will output 60ddd.
In Following Expression:
string str = "ddd" + 30 + 20 + 10;
Console.WriteLine(str);
First "ddd" + 30 got evaluates in which string + integer operation takes place so output will be ddd30.
Then ddd30 + 20 will get evaluated in which again string + integer operation takes place so output will be ddd3020.
Then ddd3020 + 10 will get evaluated in which again string + integer operation takes place so output will be ddd302010.
It happens because, the order of operations if from left to right. But assigment is last operation.
To assing value first expression must be calculated.
I'm was wondering if there is a way to format a string to format a string, what I mean is, I have a foreach loop that get a information from some files and how many records has each file, as the length of each file is different the format is change.
My example is, I have 3 files:
1.- MyFile1.txt RecordCount: 5
2.- anotherfile.txt RecordCount: 8
3.- MyTestFile.doc RecordCount: 17
As you can see are not formated, I want something like this:
1.- MyFile1.txt RecordCount: 5
2.- anotherfile.txt RecordCount: 8
3.- MyTestFile.doc RecordCount: 17
does not matter the length of the file, RecordCount will be in the same place.
What I have is this:
foreach (RemoteFileInfo file in MySession.EnumerateRemoteFiles(directory.RemoteDirectory, directory.RemoteFiles, EnumerationOptions.None))
{
BodyMessage.Append((index + 1) + ". " + file.Name + " Record Count: " + File.ReadAllLines(Path.Combine(directory.LocalDirectory, file.Name)).Length.ToString() + "\n");
index++;
}
Any idea?
You can try using \t in your strings which will insert a tab or you can try padding each portion so they always take up the same amount space.
For example:
string fileName = file.Name.PadRight(50);
will ensure that the string fileName is at least 50 characters long. I say at least because you could always have a file name that is larger than 50 characters.
foreach (RemoteFileInfo file in MySession.EnumerateRemoteFiles(directory.RemoteDirectory, directory.RemoteFiles, EnumerationOptions.None))
{
int lines= File.ReadAllLines(Path.Combine(directory.LocalDirectory, file.Name)).Length.ToString();
string appending = String.Format("{0,2}.- {1,-18} RecordCount: {3}", file.Name, lines);
BodyMessage.Append(appending);
index++;
}
See MSDN: String.Format Method.
Firstly, use string.Format, rather than concatenation:
int lineCount = File.ReadAllLines(Path.Combine(directory.LocalDirectory, file.Name)).Length.ToString();
string message = string.Format("{0}. {1}\t Record Count: " {2}\n", (index + 1), file.Name, lineCount);
To answer your question, you can align text within a formatted string using the following syntax:
string message = string.Format("{0}. {1,-10}\t Record Count: " {2}\n", (index + 1), file.Name, lineCount);
The additional -10 will ensure that the inserted text is left-padded to 10 characters.
I think you can use PadRight or PadLeft function for this.
string _line = item.FirstName.PadRight(20) + item.Number.PadRight(20) + item.State.PadRight(20) + item.Zip.PadRight(20);
file.WriteLine(_line);
I need help figuring out a logic.
I have a working code where the code will take a string and figure out every numbers in that string then add 1.
string str = "";
str = Console.ReadLine();
str = Regex.Replace(
str,
#"\d+",
m => (Double.Parse(m.Groups[0].Value) + 1).ToString()
);
Example:
If I enter "User 000079 is making $1000 from Jan 02 to Feb 24".
The code will produce output: "User 80 is making $1001 from Jan 3 to Feb 25".
The problem is, I want to keep the 0 in front of the 80 and 3. (i.e. User 000080 is making $1001 from Jan 03 to Feb 25)
How do I do that?
Additional Info: Let me clarify, this is just an example. What I want is just a way to add 1 to every number appearing in the string. So if it means UserID, January 31 - Yes, I still want them to increase by 1
This will do what you need:
string str = Console.ReadLine();
str = Regex.Replace(
str,
#"\d+",
m => (Double.Parse(m.Groups[0].Value) + 1).ToString().PadLeft(m.Groups[0].Value.Length, '0')
);
You can fix this with the ToString format like below:
String x = (50).ToString("D8"); // "00000050"
You can find more info about this here: msdn
edit: About the lengte if you do this the length will be correct:
System.Text.RegularExpressions.Regex.Replace(
str,
#"\d+",
m => (int.Parse(m.Groups[0].Value) + 1).ToString("D" + m.Groups[0].Value.Length)
);
It sounds like your user ID numbers aren't really 'numbers', but rather strings of numeric characters. Can the representation of the ID be changed to a string instead?
If you only care about the extra zeroes when rendering the ID, you can use String.Format to render the numeric value correctly using Custom Numeric Formats (specifically, see the 'Zero Placeholder' section).
What is the correct way to concatenate these elements?
Environment: C#-WinForm-Desktop.
In my app, I have a text file called config.ini. This file has values with this nomenclature:
csv_month_hour=value
The data are thus:
[csv]
csv_01_01=value // 24 hours a day in January
csv_01_02=value
csv_01_03=value
.
csv_02_01=value // 24 hours a day in February
csv_02_02=value
csv_02_03=value
.
// and so on
My app has this method called:
private void getMonthHour()
{
DateTime Xdt = DateTime.Now;
int Xmonth = Xdt.Month;
int Xhour = Xdt.Hour;
if (File.Exists("config.ini"))
{
IniFile ini = new IniFile("config.ini");
m3h = Convert.ToDouble(confg.csv["csv_" + Xmonth.ToString + "_" + Xhour.ToString]);
}
}
This method is called every seconds in timer_tick to check the month and time to use the corresponding value.
I need to know how to concatenate this:
m3h = Convert.ToDouble(confg.csv["csv_"+Xmonth.ToString+"_"+Xhour.ToString]);
An example of the code would be:
if (Xmonth==1&&Xhour==1){m3h = Convert.ToDouble(confg.csv.csv_01_01);}
else if (Xmonth==1&&Xhour==2){m3h = Convert.ToDouble(confg.csv.csv_01_02);}
else if (Xmonth==1&&Xhour==3){m3h = Convert.ToDouble(confg.csv.csv_01_03);}
// csv_month_hour in this case 01 is January.
else if (Xmonth==2&&Xhour==1){m3h = Convert.ToDouble(confg.csv.csv_02_01);}
// And so on, until December (12).
Putting aside the invalid syntax/compiler error from your method calls in your code, I suspect you're building the string but can't get the leading 0 in front of digits 0-9. So when Xmonth and Xhour are less than 10, your string is being built as "csv_1_1" instead of your intended "csv_01_01".
To instruct the ToString method to include a leading zero when needed, you can supply a custom numeric format string "00" (see the first entry in the link for "Zero placeholder").
Try using Xmonth.ToString("00") and Xhour.ToString("00"):
Monitor.malyt.m3h = Convert.ToDouble(confg.csv["csv_" +
Xmonth.ToString("00") + "_" +
Xhour.ToString("00")]);
This will output the values of Xmonth and Xhour with a single leading zero where needed.