Writing Array LineWise to a .txt file? - c#

Here is a small part of my program. here i am basically writing a .txt file when the button - 'HideItBtn' is clicked. in this piece of code first the.txt file is created then the value of the ListView SubItem - 'Folder path' is stored in a string array and that array is used to write the text file.
private void HideItBtn_Click(object sender, EventArgs e)
{
string[] strArray = new string[500];
int i = 0;
//Creat Hide.bat and write in it !
StreamWriter hide = new StreamWriter(HideNameTxt.Text + ".txt");
for (int j = 1; j < FolderList.Items[i].SubItems.Count; j++)
{
ListViewItem.ListViewSubItem cur = FolderList.Items[i].SubItems[j];
strArray[i] = cur.Text;
hide.WriteLine("attrib \" + strArray[i] + "\" + Environment.NewLine);
i++;
}
hide.Close();
}
Now the problem:
i run my application and select 3 folders from which show up in the ListView !
But the output .txt file only contains :
attrib "C:\Users\Sand\Desktop\nf"
Non of the other folder r
listed ! i added -"Environment.NewLine" at the end of .WriteLine ! but nothing happened ! Please Help ! Thanks !

You need to have two for loops, not one. Currently you're incrementing i at the end of your for loop, but you've only written one of the sub items, not all of them. You need to have a loop that goes through all items, and another loop to go through all sub-items.
private void HideItBtn_Click(object sender, EventArgs e)
{
using (StreamWriter hide = new StreamWriter(HideNameTxt.Text + ".txt"))
for (int i = 0; i < FolderList.Items.Count; i++)
for (int j = 1; j < FolderList.Items[i].SubItems.Count; j++)
{
ListViewSubItem cur = FolderList.Items[i].SubItems[j];
hide.WriteLine("attrib \"" + cur.Text + "\""
+ Environment.NewLine);
}
}

Related

Hey I need more information about this code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
private void Button4_Click(object sender, EventArgs e) {
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
using(var streamReader = new StreamReader(start)) {
string line = streamReader.ReadLine();
int[] values = line.Split(' ').Select(int.Parse).ToArray();
Array.Sort(values);
Array.Reverse(values);
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
}
}
Hey guys I need more information about this code. Could anyone explain me how it works. I mostly googled it so dont know how it works. Also I have added .txt file and got access to first row, but i need to get into 7 and 8 row. There's just random numbers in that .txt file.
Ok so there's a better way to do this. StreamReader has a .Peek() method that is extremely useful for reading to the end of a file. Basically the only thing you're missing is a way to loop through each line in your file.
Start with your using statement.
using(var streamReader = new StreamReader(start)) {...
//Using statement is a way for you to close your stream after the work
//is completed. This is why you need to get a loop inside of here.
Use a loop to read to the end of a file.
This part is what I'd change in your code. Your Using statement will not loop. You have to tell it to loop. Peek() returns -1 or the next character to be read. So you can use this to your advantage to check if you want to read to the end of file. Review the documentation here. https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.peek?view=netframework-4.8
while(streamReader.Peek() > -1)
{...
Then you can split to your array per line by simply reading in each or splitting to a character.
int[] values = streamReader.Readline().Split(' ');
Finally you can do the remainder of your code.
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
To break down exactly what is going on in your code. Read each comment line by line to get a basic understanding.
//Button Click Event
private void Button4_Click(object sender, EventArgs e) {
//Finding your file and assigning it as a string.
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
//Using a `using` statement and creating a new streamReader that will look
//for the string that you created above to find the file. The using block
//will properly close the streamreader when the work is done.
using(var streamReader = new StreamReader(start)) {
//StreamReader.ReadLine() will read the FIRST line, no loop here.
//This is why your code only reads one.
string line = streamReader.ReadLine();
//Splitting to an array.
int[] values = line.Split(' ').Select(int.Parse).ToArray();
//Sorting array.
Array.Sort(values);
//Reversing the array.
Array.Reverse(values);
//Looping through the array based on count.
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
}
}
If you're attempting to only get rows 7, 8, 9, etc.. within your for loop at the very end of your code do the following.
//Looping through the array based on count.
for (int i = 0; i < values.Length; i++) {
//This will only append rows 7-9. Keep in mind an array is a 0 based
//index. Meaning row 7 is actually array element 6. Row 9 is actually
//array element 8.
if(i > 5 && i < 9){
richTextBox4.AppendText(values[i] + " ");
}
}
}
}
So my current code looks like this:
private void Button4_Click(object sender, EventArgs e)
{
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
using (var streamReader = new StreamReader(start))
{
while (streamReader.Peek() > -1)
{
string[] values = streamReader.ReadLine().Split(' ');
Array.Sort(values);
Array.Reverse(values);
for (int i = 0; i < values.Length; i++)
{
richTextBox4.AppendText(values[i] + " ");
}
}
}

How to do a clickable file path in asp.net c#

I am trying to get a clickable file path using asp.net c# visual studios web form, meaning to say that it is like windows file explorer, allowing the person to navigate through the different levels of folders etc, can anyone provide any links to help get me started? [1]: https://i.stack.imgur.com/WyyLq.png
You could try to get the path string and divide it in multiple pieces. Then store them in multiple textboxes, labels, buttons or whatever you want. My form looks like this: Picture Form
Secondly, you will have to update those (in my case) textboxes to save the path. See my code and decide what you want to use, and if you have to modify it.
private void changePath()
{
String path = webBrowser1.Url.AbsolutePath;
if (path.Contains(#"/")) { path = path.Replace(#"/", #"\"); }
string[] directories = path.Split(Path.DirectorySeparatorChar);
int count = directories.Count();
if (count <= 6)
{
textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = "";
for (int i = 0; i < count; i++)
{
String txt = "textBox" + (i + 1);
TextBox tbx = this.Controls.Find(txt, true).FirstOrDefault() as TextBox;
tbx.Text = directories[i];
}
}
else
{
int p = count / 6;
int z = count - (p * 6);
for (int i = 0; i < count; i++)
{
int g = i - 1;
String txt = "textBox" + (i + 1);
TextBox tbx = this.Controls.Find(txt, true).FirstOrDefault() as TextBox;
tbx.Text = directories[z];
z++;
if (i == 5)
{
break;
}
}
}
}
Second step is to make click functions on the (in my case) textboxes. Here is one sample of how you can do this. See for yourself what you can do.
private void textBox5_Click(object sender, EventArgs e)
{
if(!textBox5.Text.Equals(String.Empty))
{
String p = webBrowser1.Url.AbsolutePath;
if(!textBox6.Text.Equals(String.Empty))
{
webBrowser1.Url = new Uri(p.Replace(#"/" + textBox6.Text, ""));
}
}
}
This code will remove the last piece, leaving you with a new path. Example:
Before: C:\Users\USERNAME\Desktop\C#
After:
After: C:\Users\USERNAME\Desktop
Again, you have to look what works for you. There are multiple ways to resolve your issue.
Good Luck!
Twan.

Replace multiples words in text document C#

So I'm trying to get a program running to save me copying and pasting loads of text for android studio. For this I have created listboxes with all the different bits of information required, added button click event to create a document, and another button click event to add the text into the document. So far I'm able to generate all the text when adding one set of latlongs, but I can't seem to work out how to add another set latlongs in..
For example
I need:
googleMap.addMarker(new MarkerOptions().position(new LatLng(-17.79940000000, 31.01680000000)).title(bbb));
googleMap.addMarker(new MarkerOptions().position(new LatLng(-17.80150000000,
31.03650000000)).title(ccc));
But all's I am getting is:
googleMap.addMarker(new MarkerOptions().position(new LatLng(-17.79940000000, 31.01680000000)).title(bbb));
googleMap.addMarker(new MarkerOptions().position(new LatLng(-17.80150000000, 31.01680000000)).title(bbb));
The Longitude value is not changing? I'm hoping all of this makes sense?
string path = Environment.CurrentDirectory + "/" + "latlong.txt";
private void button1_Click(object sender, EventArgs e)
{
if (!File.Exists(path))
{
File.CreateText(path);
MessageBox.Show("File has been created.");
}
}
private void button2_Click(object sender, EventArgs e)
{
using (StreamWriter stwr = new StreamWriter(path))
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
stwr.WriteLine("googleMap.addMarker(new MarkerOptions().position(new LatLng(" + listBox1.Items[i] + ", " + "ii" + ")).title(" + "bbb" + "));");
}
stwr.Close();
string text = File.ReadAllText("latlong.txt");
for (int ii = 0; ii < listBox2.Items.Count; ii++)
{
text = text.Replace("ii", Convert.ToString(listBox2.Items[ii]));
}
File.WriteAllText("latlong.txt", text);
}
}
I guess the problem is that Replace is replacing all occurences of ii, so if you debug your loop you'll see that only the first time iiis replaced by the first item in your listBox2. To solve that,i think you should add the index to ii,something like this
private void button2_Click(object sender, EventArgs e)
{
using (StreamWriter stwr = new StreamWriter(path))
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
stwr.WriteLine("googleMap.addMarker(new MarkerOptions().position(new LatLng(" + listBox1.Items[i] + ", " + "ii" + i + ")).title(" + "bbb" + "));");
}
stwr.Close();
string text = File.ReadAllText("latlong.txt");
for (int ii = 0; ii < listBox2.Items.Count; ii++)
{
text = text.Replace("ii"+ii, Convert.ToString(listBox2.Items[ii]));
}
File.WriteAllText("latlong.txt", text);
}
}
Notice that in the first loop i'm adding "ii" + i and in the second i'm replacing "ii"+ii

Loop c# - use variable in textbox

I made a loop:
for (int i = 0; i < sumUSERS; i++ )
{
principal.UserPrincipalName = "bn" + txtbox_cusnumber.Text + "." + txt_user1.Text;
}
In my Form i have Text boxes with the following names :
txt_user1
txt_user2
txt_user3
How can I set the value i in txt_user(i).text?
I hope my question is understandable.
Make an array of the boxes, and use an index, like this:
var txt_user = new [] {txt_user1, txt_user2, txt_user3};
for (int i = 0; i < txt_user.Length ; i++ ) {
principal.UserPrincipalName += "bn" + txtbox_cusnumber.Text + "." + txt_user[i].Text;
}
Note that I replaced = with +=, otherwise the text would be the same as if you used txt_user3 by itself (i.e. only the last assignment would stay).

Writing rows from a DataTable is creating a run-on write: how do I preserve each line as it is written?

Given this code:
using (StreamWriter sw = File.CreateText(file))
{
for (int r = 0; r < originalDataTable.Rows.Count; r++)
{
for (int c = 0; c < originalDataTable.Columns.Count; c++)
{
var rowValueAtColumn = originalDataTable.Rows[r][c].ToString();
var valueToWrite = string.Format(#"{0}{1}", rowValueAtColumn, "\t");
if (c != originalDataTable.Columns.Count)
sw.Write(valueToWrite);
else
sw.Write(valueToWrite + #"\n");
}
}
}
I am trying to write a DataRow back to a file one row at a time; however, the file it is creating is creating a run-on sentence where all the data being written to the file is just in one line. There should be 590 individual lines not just one.
What do I need to add to the code above so that my lines are broken out as they are in the data table? My code just doesn't seem to be working.
sw.Write(valueToWrite + #"\n"); is wrong. Because of the # it is not entering a newline, you are writing the character \ then the character n.
You want to do either sw.Write(valueToWrite + "\n"); or have the program put a new line in for you by doing sw.WriteLine(valueToWrite), however that will enter Environment.NewLine which is \r\n on windows.
However you can make your code even simpler by inserting the row the separator outside of the column for loop. I also defined the two separators at the top of the loop in case you want to ever change them (What will the program you are sending this to do when you hit some data that has a \t or a \n in the text itself?), and a few other small tweaks to make the code easier to read.
string colSeperator = "\t";
string rowSeperator = "\n";
using (StreamWriter sw = File.CreateText(file))
{
for (int r = 0; r < originalDataTable.Rows.Count; r++)
{
for (int c = 0; c < originalDataTable.Columns.Count; c++)
{
sw.Write(originalDataTable.Rows[r][c])
sw.Write(colSeperator);
}
sw.Write(rowSeperator);
}
}
Here is another similification just to show other ways to do it (now that you don't need to check originalDataTable.Columns.Count)
string colSeperator = "\t";
string rowSeperator = "\n";
using (StreamWriter sw = File.CreateText(file))
{
foreach (DataRow row in originalDataTable.Rows)
{
foreach (object value in row.ItemArray))
{
sw.Write(value)
sw.Write(colSeperator);
}
sw.Write(rowSeperator);
}
}
Change sw.Write() to sw.WriteLine()
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.writeline.aspx

Categories