I new with C# and in and I have some questions.
I'm writing some program that get the following output from remote machine (using SSH):
wwn = 5001248018b6d7af
node_wwn = 5001248018b6d7ae
wwn = 5001248118b6d7af
node_wwn = 5001248118b6d7ae
wwn = 5001248218b6d7af
node_wwn = 5001248218b6d7ae
wwn = 5001248318b6d7af
node_wwn = 5001248318b6d7ae
The output above save into string...
I need to extract from this output List or Array in the following format:
50:01:24:80:18:b6:d7:af:50:01:24:80:18:b6:d7:ae
each two lines are couple (wwn and node_wwn)
I worth the following function
public void OutPutParse (string output)
{
string wwnn = null;
string wwpn = null;
string[] test = output.Split('\n');
test = test.Where(item => !string.IsNullOrEmpty(item)).ToArray();
//run all over the test array and exrract the wwns and wwpn
for (int i = 0; i < test.Length; i++)
{
}
}
this function create an array (test) of wwns and node_wwn
the expected results is an array or list the will include wwn + node_wwn like this
50:01:24:80:18:b6:d7:af:50:01:24:80:18:b6:d7:ae
The easiest way to achieve this is:
string www = "5001248018b6d7af";
string wwwn = "5001248018b6d7ae";
string myString = "";
// Implemenet loop here.
// www = "number" // the next number you get
// wwwn = "number" // the next number you get
myString = www + myString + wwwn;
You just have to do it with a loop when you have a list of strings or something.
If you want to have it in the same order you can either do it with a character between the strings like a ";" and split all numbers or you just do two strings and combine them at the end like that:
string www = "5001248018b6d7af";
string wwwn = "5001248018b6d7ae";
string mywwwString = "";
string mywwwnString = "";
// Implement the loop to add strings here
// www = "number" // the next number you get
// wwwn = "number" // the next number you get
mywwwString += www;
mywwwnString += wwwn;
string myString = www + wwwn;
Related
I'm trying to download a file from internet to local folder with .net core, although it compiles without warnings or errors when executed it shows an error
using System;
namespace download_file
{
class Program
{
static void Main(string[] args)
{
string zip_url = #"https://www.python.org/ftp/python/3.9.5/python-3.9.5-embed-amd64.zip";
string current_directory = System.IO.Directory.GetCurrentDirectory();
string dl_path = System.IO.Directory.CreateDirectory(System.String.Format(#"{0}\DL", current_directory)).FullName;
string[] zip_url_words = zip_url.Split('/', 1);
string downloaded_file_path = System.String.Format(#"{0}\{1}", dl_path, zip_url_words[zip_url_words.Length - 1]);
// downloading the embedded python zip file
file_download(zip_url, downloaded_file_path);
void file_download(string url, string save_path)
{
if (url is null)
{
return;
}
string[] url_word_array = url.Split('/', 1);
if (save_path is null)
{
save_path = System.IO.Directory.GetCurrentDirectory() + #"\" + url_word_array[url_word_array.Length - 1]; //rsplit
}
System.Net.WebClient client = new System.Net.WebClient();
client.DownloadFile(url, save_path);
//System.Console.WriteLine("Press any key...")
//System.Console.ReadLine()
}
}
}
}
The problem is in this line:
string[] zip_url_words = zip_url.Split('/', 1);
From the documentation:
public String[] Split(char[]? separator, int count);
//
// Summary:
// Splits a string into a maximum number substrings based on the provided character
// separator.
If you add 1 as the second parameter, then you're asking the function to split the string with the separator but return "only one" value in the resulting array. The function then returns an array with only the original string because that is only way it can think to split the array with exactly-one element in the array!
Therefore the above code returns ["https://www.python.org/ftp/python/3.9.5/python-3.9.5-embed-amd64.zip"] as the value for the variable zip_url_words. Change the above code like so:
string[] zip_url_words = zip_url.Split('/');
When you make this change, then the function returns an array with the split that you expect ['https:','','www.python.org','ftp','python','3.9.5','python-3.9.5-embed-amd64.zip']
I made the change and the code works for me.
I changed
string[] zip_url_words = zip_url.Split('/', 1);
to
string[] zip_url_words = zip_url.Split('/', '1');
and
string[] url_word_array = url.Split('/', 1);
to
string[] url_word_array = url.Split('/', '1');
I downloaded
Could you try one more time?
I have this string, I want to get the part after the date. The part till date always remains the same. I would have hoped to get the index of date but it changes always hence I can't use it.
var str = "c:\ somefolder\ download\ 2019-14-11 merchandise of today"
char[] spearator = {" "};
var _split = str.Split(spearator);
Here I have all the words broken down according to spaces.
How do I get the 'merchandise of today'?
You can try following codes, use the regular expression
var str = #"c:\ somefolder\ download\ 2019-14-11 merchandise of today";
var reg = new Regex(#".+\d{4}-\d{2}-\d{2}");
var result = reg.Replace(str, string.Empty).Trim();
If the format of the date does not change, you could do the following:
var path = #"C:\Example\Download\2019-14-11 Merchandise Of Today";
var merchandise = path.Substring(path.LastIndexOf('\\')).Trim();
OR
var merchandiseWithoutDate = path.Substring(path.IndexOf(' ').Trim();
That will output the date and merchandise of today, if you change the character to a space you will also retrieve that.
What Substring is basically allows you to control an index to begin and end, which allows you to mitigate the text received.
//Thanks guys!
//This is what I did before I saw the two answers. I know it is messy a lot and now I am //gonna try the substring method but this was a temporary fix for me. Thanks again!
var str = "c:\ somefolder\ download\ 2019-14-11 merchandise of today"
char[] spearator = {" "};
var _split = str.Split(spearator);
int len = _split.lenght-1;
for(i=0; i<_split.lenght; i++)
{
var getStr = _split[i]
Match search = regex.match(getStr, "my regex patern for date");
if (search.success)
{
var converted = search.tostring();
int index = Array.IndexOf(_split, converted)
index++;
string temp = "";
while(index<=len_)
{
string temp = temp+ " "+_split[index];
index++;
}
console.writeline("String is {0}", temp);
}
}
i have a string Like
"Hello i want to go."
my code give "want to go."
but i need string between " i " and " to " how can i get this? my code is as below.
string[] words = Regex.Split("Hello i want to go.", " i ");
string respons = words[1];
string input = "Hello i want to go.";
Regex regex = new Regex(#".*\s[Ii]{1}\s(\w*)\sto\s.*");
Match match = regex.Match(input);
string result = string.Empty;
if (match.Success)
{
result = match.Groups[1].Value;
}
This regex will match any 'word' between 'i' (not case sensitive) and 'to'.
EDIT: changed ...to.* => to\s.* as suggested in the comments.
string input = "Hello I want to go.";
string result = input.Split(" ")[2];
If you want the word after the "i" then:
string result = input.Split(" i ")[1].Split(" ")[0];
Use
string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor
just do it with one simple line of code
var word = "Hello i want to go.".Split(' ')[2];
//Returns the word "want"
string input = "Hello I want to go.";
string[] sentenceArray = input.Split(' ');
string required = sentenceArray[2];
Here's an example using Regex which gives you the index of each occurrence of "want":
string str = "Hello i want to go. Hello i want to go. Hello i want to go.";
Match match = Regex.Match(str, "want");
while(match.Success){
Console.WriteLine(string.Format("Index: {0}", match.Index));
match = match.NextMatch();
}
Nowhere does it say Regex...
string result = input.Split.Skip(2).Take(1).First()
it's work
public static string Between(this string src, string findfrom, string findto)
{
int start = src.IndexOf(findfrom);
int to = src.IndexOf(findto, start + findfrom.Length);
if (start < 0 || to < 0) return "";
string s = src.Substring(
start + findfrom.Length,
to - start - findfrom.Length);
return s;
}
and it can be called as
string respons = Between("Hello i want to go."," i "," to ");
it return want
I currently have a conf file which exists out of the following format:
[client]
person1,person2,person3,person4
[employee]
emp1,emp2,emp3,mp4
And so on. Now I need to read the file to store the data that comes after the line [employee] into and array.
As a quick draft, try something like this:
string[] readAllLines = File.ReadAllLines("path/to/file");
for (int i = 0; i < readAllLines.Length-1; i++)
{
if (readAllLines[i].StartsWith("[employee]"))
{
string[] employees = readAllLines[i + 1].Split(',');
// Do something
}
}
Untested Code:
static class SubstringExtensions
{
/// <summary>
/// Get string value after [last] a.
/// </summary>
public static string After(this string value, string a)
{
int posA = value.LastIndexOf(a);
if (posA == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
if (adjustedPosA >= value.Length)
{
return "";
}
return value.Substring(adjustedPosA);
}
}
Read the File:
System.IO.StreamReader myFile = new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
string[] split = myString.After("[employee]").Split(',');
Not the most cool or elegant way, but the way you described it would work like this.
StreamReader reader = new StreamReader("path to your config file");
string text = reader.ReadToEnd();
text = text.Substring(text.IndexOf("[employee]"), 25);
text = text.Replace("[employee]\r\n", "");
string[] array = text.Split(',');
I want to read words in a text file of a line separated by commas in c sharp.
For example, I want to read this line:
9/10/2011 10:05,995.4,998.8,995.4,997.5,118000
and get the values: 9/10/2011 10:05, 995.4, 998.8, 995.4, 997.5 and 118000.
Next, I also need to change the format of the date to MMddYYYY, and of the time to HHmmss (e.g. 100500).
I am using this code for reading is there anything wrong
private void button1_Click(object sender, EventArgs e)
{
StreamReader reader1 = File.OpenText(Path1);
string str = reader1.ReadToEnd();
reader1.Close();
reader1.Dispose();
// File.Delete(Path1);
string[] Strarray = str.Split(new char[] { Strings.ChrW(7) });
int abc = Strarray.Length - 1;
int xyz = 0;
bool status = true;
while (xyz <= abc)
{
try
{
status = true;
string[] strarray1 = Strarray[xyz].Split(",".ToCharArray());
string SecName = strarray1[0];
int a2 = 0;
while (status) //If the selected list is empty or the text file has selected name this will execute
{
status = false;
string SecSym = strarray1[1];
int DT = int.Parse(strarray1[2]);
int TM = int.Parse(strarray1[3]);
float O = float.Parse(strarray1[2]);
float H = float.Parse(strarray1[3]);
float L = float.Parse(strarray1[4]);
float C = float.Parse(strarray1[5]);
double OI = double.Parse(Convert.ToString(0));
float V = float.Parse(strarray1[6]);
// string a = string.Concat(SecName, ",",SecSym,",", DT, ",", TM, ",", O, ",", H, ",", L);
//writer.WriteLine(a);
}
}
catch
{ }
}
}
}
.Net comes with a ready CSV parser you can use to get your data. It's a part of VB.net, but you can easily use it in C# by adding a reference to the assembly Microsoft.VisualBasic (it's OK, honesly), and a using statement: using Microsoft.VisualBasic.FileIO;.
The code should be simple to understand:
List<String[]> fileContent = new List<string[]>();
using(FileStream reader = File.OpenRead(#"data.csv")) // mind the encoding - UTF8
using(TextFieldParser parser = new TextFieldParser(reader))
{
parser.TrimWhiteSpace = true; // if you want
parser.Delimiters = new[] { "," };
parser.HasFieldsEnclosedInQuotes = true;
while (!parser.EndOfData)
{
string[] line = parser.ReadFields();
fileContent.Add(line);
}
}
CSV is fairly simple, but it may contain quoted values with commas and newlines, so using Split isn't the best option.
Use the String.Split method to get an array of strings:
string[] ar = line.Split(',')
This should get you started.
using System;
using System.IO;
public class Sample
{
public static void Main() {
using (StreamReader reader = new StreamReader("yourfile.txt")) {
string line = null;
while (null != (line = reader.ReadLine())) {
string[] values = line.Split(',');
DateTime date = DateTime.Parse(values[0];
float[] numbers = new float[values.Length - 1];
for (int i = 1; i < values.Length - 1; i++)
numbers[i - 1] = float.Parse(values[i]);
// do stuff with date and numbers
}
}
}
}
I have also posted a simple CsvReader class which may be helpful for you.
For a quick and simple solution, you can stream through the file and parse each line using String.Split like this:
using (var sr = File.OpenText("myfile.csv"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
var fields = line.Split(',');
var date = DateTime.Parse(fields[0].Trim());
var value1 = fields[0].Trim();
}
}
However, this appraoch if fairly error prone, for a more robust solution check out the CsvReader project, it's excellent for parsing CSV files like this. It will handle field values with commas, trimming spaces before and after fields, and much more.
If you need to parse a date string from a format not recognised by DateTime.Parse, try using DateTime.ParseExact instead.
For 1st part of your task use Split method with , as separator. To convert string datetime from one format to another you need to convert that string to datetime(DateTime.Parse, DateTime.ParseExact) and then convert to final format using DateTime.ToString method.
rows contain your output
StreamReader sStreamReader = new StreamReader("File Path");
string AllData = sStreamReader.ReadToEnd();
string[] rows = AllData.Split(",".ToCharArray());