Here's my code:
for (int j = 0; j < bufferreader.Length; j++)
{
using (StreamWriter sw = File.AppendText(#"C:\Users\yamald\Documents\Normal.data"))
{
//sw.Write();
if (bufferreader.length != null)
{
sw.Write(bufferreader[j] + ",");
}
else
{
sw.WriteLine("\n");
}
}
}
How can I write a "\n" at the end of array to my file? The else command does not run.
You need to place sw.WriteLine("\n"); after the for loop.
As the loop stops when j = bufferreader.length, the if statement is always true.
Also, I think that bufferreader.length will never be null as you never modify this variable. I think what you need is :
if (bufferreader.length > j)
You should probably just make the StreamWriter object before everything else and have it available until the loop has finished, then just write the newline after the loop, like this:
using (StreamWriter sw = File.AppendText(#"C:\Users\yamald\Documents\Normal.data"))
{
for (int j = 0; j < bufferreader.Length; j++)
{
sw.Write(bufferreader[j] + ",");
}
sw.WriteLine("\n");
}
It's also probably better to use a while loop and do something like while(bufferreader.length != null) instead of the for loop and if statement, but that's up to you and I haven't used bufferreader in a while so wouldn't know the exact syntax for that.
However, the reason for why the else never gets executed is (as EoiFirst correctly said) that you're not actually changing bufferreader.length so it won't ever be null.
Related
Hey I'm in a situation where I have a for loop that does some stuff and I want to make a line of code either call a function passing in an array indexed by the for loops index, or run a single (not array) variable for every call of that function, I know I could do that by putting an if statement inside the for loop but i'd be repeating the same if statement over and over getting the same result. So is there a way good way I can run the if statement before the for loop and the result of that if statement run the same for loop but that one call passes in the array or the variable?
Code Example
for (int i = 0; i < CurrentVerticalList.Count; i++)
{
GuiGeneral CGroup = CurrentVerticalList[i];
CGroup.ResizeUsingStandard(ForcedResize[i]); //I want the condition before the for
//loop to have ForcedResize[i] here if
//true and another variable here of the
//same type but not an array if false.
for (int j = 0; j < 2; j++)
{
GlobalListIndex[j]++;
}
CGroup.MoveElementTo(CCoord, false);
CCoord.y += CGroup.ElementRect.WidthHeight.y;
}
Here you go, moving your condition check out of your for loop:
Func<int, double> GetResizeFromForcedResize = (index => ForcedResize[index]);
Func<int, double> GetResizeFromVariable = (index => fixVariable);
var GetResizeValue = condition? GetResizeFromForcedResize : GetResizeFromVariable;
for (int i = 0; i < CurrentVerticalList.Count; i++)
{
GuiGeneral CGroup = CurrentVerticalList[i];
CGroup.ResizeUsingStandard(GetResizeValue(i));
for (int j = 0; j < 2; j++)
{
GlobalListIndex[j]++;
}
CGroup.MoveElementTo(CCoord, false);
CCoord.y += CGroup.ElementRect.WidthHeight.y;
}
Edit: Wanted to let you know that the other answers here are still doing a check at every iteration, but not this one.
Eh, hard to understand the question to me but i recon what you want is something along these lines, could've helped with more types supplied, but you could make the intend achievable using a local function:
ForcedResizeArrayType other = new object(); //TODO: Define return type
bool condition = ResolveCondition(); //TODO: Define condition to be true or false
ForcedResizeArrayType GetOneOr(int i, bool condition,
ForcedResizeArrayType[] forcedResizeArray)
{
return condition ? forcedResizeArray[i] : other;
}
for (int i = 0; i < CurrentVerticalList.Count; i++)
{
CGroup.ResizeUsingStandard(GetOneOr(i, condition, ForcedResize));
}
It varies from week to week if i love or hate those local functions, but they have uses
I am currently working on an assignment for school where I am trying to write a 2D string array into a text file. I have the array and know its working fine however every time I try to read the file into Streamwriter I get "System.ArgumentException: 'Illegal characters in path.'". I am relatively new to C# and I have no idea how to fix this.
This is my code. I just need to know how to write my 2D array into the text file without getting this error. Thanks, all and any help is much appreciated!
// This line under is where the error happens
using (var sw = new StreamWriter(Harvey_Norman.Properties.Resources.InventoryList))
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
sw.Write(InventoryArray[i, j] + " ");
}
sw.Write("\n");
}
sw.Flush();
sw.Close();
}
My guess is that Harvey_Norman.Properties.Resources.InventoryList is a resource in your project that is typed as a string-- and the value of that string is not a valid path for your operating system.
StreamWriter will either take a string, in which case it expects to open a file with the path of that string; or it will take a stream, and you can write to that stream. It looks like you are trying to do the former; but you need to check the value of that resource to see if it is a vaild path.
You're trying to construct a StreamWriter with an invalid file path.
Also, if you're just writing text out, you can use File.CreateText() to create a StreamWriter, for example:
var tempFilePath = Path.GetTempFileName();
using (var writer = File.CreateText(tempFilePath))
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
if (j > 0)
writer.WriteLine(" ");
writer.Write(InventoryArray[i, j]);
}
writer.WriteLine();
}
}
The using will automatically flush and close the file, and dispose the StreamWriter.
So I've been woking a Console game for a while now and I desided to use .txt files to hold the maps. This code opens and stores the txt file contents:
static void LoadMap(string fname)
{
string _org = File.ReadAllText("Maps/" + fname + ".txt");
_org.Split(',');
string[] _tmp = new string[_org.Length];
for (int i=0;i<_org.Length;i++)
{
_tmp[i] = _org[i].ToString();
}
//This line has the error
for (int i=0;_tmp[i]!="$";i+=2)
{
mapwidth += 1;
}
for (int i=0;i<_tmp.Length;i++)
{
leveldata.Add(_tmp[i]);
}
}
I get this error: Index was outside the bounds of the array. I can't figgure out why. Can anyone help? Thanks
Check that variable i does not take values beyond the Length - 1 of the array.
static void LoadMap(string fname)
{
string _org = File.ReadAllText("Maps/" + fname + ".txt");
_org.Split(',');
string[] _tmp = new string[_org.Length];
for (int i = 0;i < _org.Length; i++)
{
_tmp[i] = _org[i].ToString();
}
for (int i = 0;i < _tmp.Length && _tmp[i] != "$"; i += 2)
{
mapwidth += 1;
}
for (int i = 0;i < _tmp.Length; i++)
{
leveldata.Add(_tmp[i]);
}
}
I am not super sure what you are getting at here but I feel a foreach may be a step in the right direction.
First, here are a few things I noticed in the code you presented.
string _org = File.ReadAllText("Maps/" + fname + ".txt");
_org.Split(',');
Here you have ingested your text file and split _org with a comma delimiter. Though you never actually assigned the split array to a variable. _org is still a string, not a string[].
string[] _tmp = new string[_org.Length];
for (int i = 0; i < _org.Length; i++)
{
_tmp[i] = _org[i].ToString();
}
In this block we have set _tmp as a string array using the length of _org. The Length property in this case will retrieve the number of characters in the string _org. assuming _org is set to "foo" the size of the _tmparray is now 3. (0,1,2)
You then go on to load _tmp with the nth character of _org converted to a string.
At this point we have the following in our variables.
_org = "foo"
_tmp = {"f","o","o"}
This next part caught me a bit off guard as I cant tell for certain what you are trying to accomplish.
for (int i = 0; _tmp[i] != "$"; i += 2)
{
mapwidth += 1;
}
You are in a for loop until _tmp[i] equals "$", and you are adding 2 to i every time you move through the loop using i += 2. This logic will break the loop until it hits a "$", or if i grows outside of the bounds of the array it will throw an exception.
You then go on to add one to the mapwidth for every two increments of i
In this final block you are adding the contents of the _tmp array to leveldata
for (int i = 0; i < _tmp.Length; i++)
{
leveldata.Add(_tmp[i]);
}
Now for the good stuff, foreach.
I have made the assumption you wanted to set _org as an array, and that you wanted everything that was not a "$". That in mind, this should accomplish what you were going for, though I am not sure the purpose of incrementing by 2 in the second for loop so I have left that out for now.
static void LoadMap(string fname)
{
string[] _org = File.ReadAllText("Maps/" + fname + ".txt").Split(',');
foreach (var _tmp in _org)
{
if (_tmp != "$")
{
mapwidth += 1;
}
leveldata.Add(_tmp);
}
}
If you want to continue coding it is always a good idea to get a good grasp on the basics.
Though a bit dated here is a good tutorial by Microsoft for programming basics in C#:
C# Programmer's Reference
Try this link.
https://www.programiz.com/csharp-programming/foreach-loop
Have suggestion keyword to avoid Index was outside the bounds of the array error.
Sample code.
for(int i = 0; i < myArray.Length; i++)
{
// Coding to Array for loop.
}
Hello I have this line of code to write every line of richTextBox into my .txt file but at the final the txt file is empty but when debug it reads every line. May I know how this code should be improved to do what I want?
string Path = (#"C:\Users\x\Documents\Visual Studio 2012\Projects\MTest\txtCmdLog.txt");
StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append));
for (int i = 0; i <= txtCmdLog.Lines.Length; i++)
{
sw.WriteLine(txtCmdLog.Lines[i] + "\n");
}
sw.Close();
Thank you for your time.
Change your loop to:
for (int i = 0; i < txtCmdLog.Lines.Length; i++)
{
sw.WriteLine(txtCmdLog.Lines[i]);
}
Don't use <= in the loop's condition check. You also don't need to append a newline character in the call to WriteLine, since that method already writes a newline.
Points to remember:
1.you need to loop through 0 to lines.Length-1.so remove = in <= condition.
2.for disposing the StreamWriter object use using{} block so that you don't need to call close().
Diposal of StreamWriter object will be taken care by using {} block
string Path = (#"C:\Users\x\Documents\Visual Studio 2012\Projects\MTest\txtCmdLog.txt");
using(StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append)))
{
for (int i = 0; i < txtCmdLog.Lines.Length; i++)
{
sw.WriteLine(txtCmdLog.Lines[i] + "\n");
}
}
The easy way to do this is:
File.WriteAllLines(filename, arrayOfStrings);
I'm new here and I tried looking through old questions but I am new to c# as well, and I am finding it difficult to solve my problem below:
if (File.Exists(#"C:\ESC\Impostazioni.txt"))
{
TextReader lettore_file = new StreamReader(#"C:\ESC\Impostazioni.txt");
String opzioni = lettore_file.ReadLine();
int i;
for (i = 0; i < opzioni.Length; i++) <----here, indicating "i=0"
{
if (opzioni[i] == '-')
{
char[] coloregenerale = new char[i];
for (int j = 0; j < i; j++)
coloregenerale[j] = opzioni[j];
break;
You should put a check to see if the string value is null or empty before trying to loop through each character, like this:
if(!String.IsNullOrEmpty(opzioni))
{
// Put loop through character logic here
}
You need to debug through and find out if your opzioni string is a null reference after your call to String opzioni = lettore_file.ReadLine();
Also, you should probably declare i within the for loop, instead of before it, like shown below.
for (int i = 0; i < opzioni.Length; i++)
There are several wrongs inside that code:
You're missing a using statement.
You're not checking the result of StreamReader.ReadLine.
It looks like you're reimplementing string.Substring.
Sample:
if (File.Exists(#"C:\ESC\Impostazioni.txt"))
{
using (var letterFile = new StreamReader(#"C:\ESC\Impostazioni.txt"))
{
var opzioni = letterFile.ReadLine();
if(string.IsNullOrWhiteSpace(opzioni))
{
// end of file
}
var dashIndex = opzioni.IndexOf("-");
string coloregenerale = dashIndex > -1
? opzioni.Substring(0, dashIndex)
: opzioni;
}
}
If your null reference exception is occurring on the indicated line, the culprit is probably the opzioni variable. If the earlier call to lettore_file.ReadLine() returns null, opzioni will be null when you try to get it's length in the for loop. That will throw the exception you're experiencing. A solution is to check that variable for null before entering the loop
The opzioni may have the chances of null value on that particular index, better handle inside of that line with IsNullorEmpty Condition
char[] coloregenerale = new char[i];
for (int j = 0; j < i; j++)
{
if( String.IsNullOrEmpty(opzioni[j] == false ) // This is mandatory check at this place
coloregenerale[j] = opzioni[j];
}