Split result of WebClient.DownloadString into multiple lines [duplicate] - c#

This question already has answers here:
split a string on newlines in .NET
(17 answers)
Closed 3 years ago.
I am trying to get a line foreach line in a webclient.DownloadString("pastebinsite"); but it says cannot convert type 'char' to 'string', so I add a string[] downloaded = wc.DownloadString(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
that does not work because it says cannot convert type 'string' to 'string[]' I am stuck and cannot find a answer online for this.
I have tried changing types
{
StringBuilder sb = new StringBuilder();
Console.WriteLine("start?");
Console.ReadKey();
string[] lines = File.ReadAllLines(Directory.GetCurrentDirectory() + #"\Lines.txt");
WebClient wc = new WebClient();
int _checked = 0;
int _error = 0;
foreach(string line in lines)
{
++_checked;
//Pastebin text viewer
try
{
if (line.Contains("pastebin"))
{
var arac = line.Split('/');
//ERROR LINE CANNOT CONVERT TYPE 'STRING' TO 'STRING[]' Below
string[] downloaded = wc.DownloadString(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
foreach(string line2 in downloaded)
{
if (line2.Contains(":")
{
//Console.WriteLine(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
Console.WriteLine(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
sb.Append(downloaded);
}
}
}
else
{
//Console.WriteLine("Not valid pastebin link!");
}
Console.Title = "Checked : " + _checked;
}
catch(WebException ex)
{
++_error;
Console.WriteLine("Error: " + _error);
}
}
File.WriteAllText(Directory.GetCurrentDirectory() + #"\Output " + _checked + ".txt", sb.ToString());
Console.Clear();
Console.WriteLine("FINISHED");
Console.ReadKey();
}```

wc.DownloadString(..)
returns a string and not a string[].
you need to split the string in order to get a string[]
possible solution if you need that the string[] will contain lines would be:
var stringResult = wc.DownloadString(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
then one of the following:
var lines = stringResult.Split(new [] { '\r', '\n' });
var lines = Regex.Split(stringResult, "\r\n|\r|\n");
var lines = stringResult.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.None)
and finally
foreach(string line in lines) {...}

Related

C# - Get All Words Between Chars

I have string:
string mystring = "hello(hi,mo,wo,ka)";
And i need to get all arguments in brackets.
Like:
hi*mo*wo*ka
I tried that:
string res = "";
string mystring = "hello(hi,mo,wo,ka)";
mystring.Replace("hello", "");
string[] tokens = mystring.Split(',');
string[] tokenz = mystring.Split(')');
foreach (string s in tokens)
{
res += "*" + " " + s +" ";
}
foreach (string z in tokenz)
{
res += "*" + " " + z + " ";
}
return res;
But that returns all words before ",".
(I need to return between
"(" and ","
"," and ","
"," and ")"
)
You can try to use \\(([^)]+)\\) regex get the word contain in brackets,then use Replace function to let , to *
string res = "hello(hi,mo,wo,ka)";
var regex = Regex.Match(res, "\\(([^)]+)\\)");
var result = regex.Groups[1].Value.Replace(',','*');
c# online
Result
hi*mo*wo*ka
This way :
Regex rgx = new Regex(#"\((.*)\)");
var result = rgx.Match("hello(hi,mo,wo,ka)");
Split method has an override that lets you define multiple delimiter chars:
string mystring = "hello(hi,mo,wo,ka)";
var tokens = mystring.Replace("hello", "").Split(new[] { "(",",",")" }, StringSplitOptions.RemoveEmptyEntries);

c# Windows Form, replace string in textbox (file content) with another string

I have a textbox that contains all of the lines of a loaded file.
It looks like this:
I am able to load a specific line of the file that contains a specific string using this in the app:
How would I be able to update the file/main textbox after I press the "Edit Module" button, if any of the textboxes would be changed .
For example, I would change Exam Weighting: "0.4" to Exam Weighting: "0.6", then press the "Edit Module" button which would edit the main textbox(file content). Which then would allow me to save the file with the updated content.
This is the code I am using to get a specific line from the file based on string from a textbox:
private void editModuleButton_Click(object sender, EventArgs e)
{
citation = editModuleComboBox.Text;
citationChange();
}
private void citationChange()
{
List<string> matchedList = new List<string>();
string[] linesArr = File.ReadAllLines(fileName);
//find matches
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
//output
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
}
If somebody with enough rep could insert the images to this post, that would be great. Thanks
This solution might not be the perfect, but should work for you. What you need to do is whenever the Edit Module button is pressed, create a new string based on the text fields and replace it with the original line. First declare a string variable private string ChangedString = ""; inside the class, then:
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
string Stream = lineData[0]; //Store this somewhere so that it can be accessed later
string Stage = lineData[1]; //Store this somewhere so that it can be accessed later
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
store Stream and Stage in any Textbox/ComboBox if you already haven't then replace them accordingly in the following line. Now in EditButton_Click [Click Event] write:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
Now replace this string with the original line.
Edit: As you would get the line number which is being edited, store it in a variable, let's say
int LineBeingEdited = 3 //Supposing line number three is being edited.
Then again in the same Click event you can write this:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
var lines = TextBox1.Lines;
lines[LineBeingEdited] = ChangedString;
TextBox1.Lines = lines;
EDIT 2: To get the line number I would suggest you to modify your for each loop to for loop. Also add a int variable to store the line number inside the class like : private int LineBeingEdited = 0;
Modify this for each :
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
To for loop:
for (int a = 0; a < linesArr.Length; a++)
{
if (s.Contains(citation))
{
matchedList.Add(linesArr[a]); //matched
LineBeingEdited = a;
break; //breaks the loop when a match is found
}
}
The above method is being used, taking into consideration that there will always be a single match. LineBeingEdited will now have the line number and can be accessed from anywhere in the class

Need Help the best overloaded method match for 'string.endswith(string)' has some invalid arguments

dynamic counter = 1;
string FileNameWithoutExtestion = "";
FileNameWithoutExtestion = file.Split('.')[0];
string FileExtestion = file.Split('.')[1];
while (System.IO.File.Exists(Dir + file))
{
if (true)
{
counter = counter + 1;
if (FileNameWithoutExtestion.EndsWith('_'))
{
file = FileNameWithoutExtestion + counter.ToString() + "." + FileExtestion;
}
else
{
file = FileNameWithoutExtestion + "_" + counter.ToString() + "." + FileExtestion;
}
}
}
if (FileNameWithoutExtestion.EndsWith('_')) //the error occurred here
Whats wrong ?
String.EndsWith() only has overloads with string as parameter, you insert a char.
Replace
.EndsWith('_')
with
.EndsWith("_")
and i would use those path-methods to parse filenames and extensions
string FileNameWithoutExtestion = System.IO.Path.GetFileNameWithoutExtension(file);
string FileExtestion = System.IO.Path.GetExtension(file); //.jpg
because FileNameWithoutExtestion = file.Split('.')[0]; will lead to a invalid value in case of a filename like foo.bar.jpg

GetFiles of certain extension and write to spreadsheet C#

I'm writing a application that reads Ia directory contents and writes that to a csv file. I'm trying to get a list of certain file extensions from and upload path which contains a csv file and write a list of the filtered extensions to a new csv file.
I cant figure out how to get the filtered csv file written.....
Here's my method.
StringBuilder CreateUserFileUploadList(SLDocument document, StringBuilder destroyWorksheet)
{
document.SelectWorksheet("User Folder");
var stats = document.GetWorksheetStatistics();
var rowcount = stats.EndRowIndex + 1;
List unwantedExtensions = cblExtensions.Items.Cast().Where(li => li.Selected).Select(li => li.Text).ToList();
if (!String.IsNullOrEmpty(tbOtherExtensions.Text))
{
unwantedExtensions.AddRange(tbOtherExtensions.Text.ToUpper().Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
}
unwantedExtensions.AddRange("EXE,COM,BAT,JS,VBS,PIF,CMD,DLL,OCX,PWL".Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
// new CSV file
var workSheet = new StringBuilder();
workSheet.AppendLine("FILEPATH,Client,Matter,LAST MODIFIED DATE,CREATED DATE,CREATED BY,LAST MODIFIED BY,FOLDER,DOCUMENT NAME,Author,Practice Area,Document Type,ACCESS,Keywords - Comments");
// loop through the directories
for (int i = 2; i 100 chars, or including TAB / \ : * ? " |
// Folder has folders>500 or has files>1000
//TODO: this loops through leaf folders; we need to check intermediate folders to ensure they don't have too many files or folders or a bad name
//Took out #"\",
bool invalidFolderName = new string[] { "/", ":", "*", "?", "" }.Any(s => directoryName.Contains(s));
if (invalidFolderName || directoryName.Length > 200 || files.Count() > 1000)
{
System.Diagnostics.Debug.WriteLine("INVALID folder: " + directoryName);
lblError.Text = lblError.Text + "\r\n" + "INVALID folder: " + directoryName;
//TODO: This should cause the WHOLE upload to fail
}
// build the target folder path
string folder;
string[] stringSeparators = new string[] { tbAuthor.Text };
var path = directoryName.Split(stringSeparators, StringSplitOptions.None);
folder = path.Last();
if (path.Count() > 1)
{
folder = ConfigurationManager.AppSettings["NetDocumentsFolderPath"].ToString() + tbAuthor.Text + #"\User Folder" + folder;
if (folder.Substring(folder.Length - 1, 1) == #"\")
{
folder = folder.Substring(0, folder.Length - 1);
}
}
// Get the files
foreach (var file in files)
{
// Remove unwanted extensions
if (!unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{
var access = file.GetAccessControl();
string user = access.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
//TODO: FWIW, fileName (on netdocs) does NOT need to match the name in the original location...
string fullName = file.FullName;
string fileName = file.Name;
// Wrap in quotes if there are any invalid characters
if (fullName.IndexOfAny(csvTokens) >= 0)
{
fullName = "\"" + fullName.Replace("\"", "\"\"") + "\"";
}
if (fileName.IndexOfAny(csvTokens) >= 0)
{
fileName = "\"" + fileName.Replace("\"", "\"\"") + "\"";
}
if (!document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{
String practiceArea = GetPracticeAreaForClientMatter(document.GetCellValueAsString(i, 2), document.GetCellValueAsString(i, 3));
String documentType = ConfigurationManager.AppSettings["FileDocumentType"].ToString();
// Validate file
// Invalid file names (>200 chars, or TAB / \ : * ? " |
// Invalid file size (>200 MB)
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
//TODO: This should cause the WHOLE upload to fail
}
else
{
workSheet.AppendLine(
fullName + "," +
document.GetCellValueAsString(i, 2) + "," +
document.GetCellValueAsString(i, 3) + "," +
file.LastWriteTime + "," +
file.CreationTime + "," +
tbAuthor.Text + "," +
tbAuthor.Text + "," +
folder + "," +
fileName + "," +
tbAuthor.Text + "," +
practiceArea + "," +
documentType + "," +
practiceArea + "|V," +
"Imported from Departed Attorney on: " + DateTime.Now.ToString("G"));
}
}
else
{
destroyWorksheet.AppendLine(fullName);
}
}
}
}
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{// Files in folders marked "destroy" are saved elsewhere
//destroyWorkSheet.Append(string.Format("{0}", "Directory" + fullName));
//destroyWorkSheet.Append(string.Format("{1}", "FileName" + fullName));
// destroyWorkSheet.AppendLine("Directory, FileName");
// destroyWorkSheet.Append(string.Format("{0},{1}", "Directory", "FileName") + fullName);
destroyWorksheet.AppendLine(fullName);
}
// Validate file for name (less than 200 chars, can't have TAB / \ : * ? " | ) and size ( less than 200 MB)
else if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{// This should cause the WHOLE upload to fail
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
errorWorksheet.AppendLine("INVALID file: " + file.Name);
}
else if (unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{// Files with unwanted extensions are filtered out
filterWorksheet.AppendLine(fullName);
}

C# - writing a line to text file after a specific line

I have the following code below and I am trying to ensure that the
line(sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype)) ;
is written out to the text file after the line(sw.WriteLine(errLine));.
At the moment when the file is created the lines are not being written to the file in the right order i.e.
sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype) - this line appears first
sw.WriteLine(errLine) - appears second.
Just wondering could you help.
using (StreamWriter sw = File.AppendText(#"D:\Temp\Final.txt"))
try
{
string evnt = Convert.ToString(eventid);
string test = Convert.ToString(testid);
Queue<string> lines = new Queue<string>();
using (var filereader = new StreamReader(#"D:\Temp\Outlook.txt"))
{
string line;
while ((line = filereader.ReadLine()) != null)
{
if (line.Contains(evnt) && line.Contains(test) && evnt != oldevent)
{
sw.WriteLine("----- ERROR -----");
foreach (var errLine in lines)
sw.WriteLine(errLine);
oldevent = evnt;
sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype);
sw.WriteLine(line);
sw.WriteLine("-----------------");
}
lines.Enqueue(line);
while (lines.Count > 10)
lines.Dequeue();
}
}
}
File is being written from up to bottom. Try taking this line
sw.WriteLine("Test Id: " + testid + " " + "Failed On Event: " + testtype); out of the for loop, before line: foreach (var errLine in lines)
As above you can do below:
File.WriteAllLines(#"D:\Temp\Final.txt", File.ReadLines(#"D:\Temp\Outlook.txt")
.Select(line => line.Contains("Something to find")
? new String[] {"Some caption", line, "More text"}
: new String[] {line};
)
.SelectMany(line => line));
May be Linq is a solution? Something like that:
var source = File
.ReadLines(#"D:\Temp\Outlook.txt")
.Select(line => {
//TODO: put actual code here
if (line.Contains("Something to find"))
return new String[] {"Some caption", line, "More text"};
else
return new String[] {line};
})
.SelectMany(line => line);
File.WriteAllLines(#"D:\Temp\Final.txt", source);

Categories