I have a class which is creating a list of objects called manufacturers. I use an XML file to create the objects which are stored in an arrayed called ManufacturerList.
Below is code from the ManufacturerImport class. This is where I create the objects.
private List<Manufacturer> ManufacturerList = new List<Manufacturer>();
public void AddManufacturer(Manufacturer manu)
{
ManufacturerList.Add(manu);
}
public List<Manufacturer> GetManufacturers()
{
return ManufacturerList;
}
As you can see, I need to pass this list to other parts of my code so I have a GetManufacturers function.
In my Main function I am using the following code:
List<Manufacturer> mList = ManuImport.GetManufacturers();
TextWriter tw = new StreamWriter(@"C:\manu.txt");
foreach (Manufacturer manu in mList)
{
//Output name to txt file.
tw.WriteLine(manu.ManufacturerName);
Console.WriteLine(manu.ManufacturerName);
Console.WriteLine(manu.ShortManufacturerName);
Console.WriteLine(manu.ManufacturerDirectory);
Console.WriteLine(manu.ManuId);
Console.WriteLine("------------------------");
}
//Forgot to include this in example. Has been in code from beginning. sorry for confusion
tw.Close();
I have debugged the code and found that the list is successfully being copied over to mList. I am a little confused as to how the mList list can contain all the objects I require but when I step through the list, I dont get the correct output.
My list has 486 objects but the output only writes 333 of those to the txt file. What is also odd is that the console outputs different manufacturers to the list.
Any thoughts would be great.
Cheers
You need to enclose your
TextWriterobject in ausingblock.There are two reasons for this:
First, fundamentally,
TextWriterimplementsIDisposable, which means that you should always callDispose()when you’re finished with the object. Theusingblock in C# and VB.NET are language-specific mechanisms for ensuring thatDisposegets called. This is true for all objects that implementIDisposable, so it’s probably a good idea to look at other areas of your code and other framework objects that you’re using to ensure that you’re following this pattern. Some things you might want to pay particular attention to are:Second, for this particular case, the
TextWriterclass buffers the data that gets written (so, for example, if you write the data a character at a time, you don’t have disk IO for EVERY character, since it does it in “chunks”). As a result, the buffer has to be flushed in order for data to get written to the disk. This happens under three cases:TextWritereither by callingClose()orDispose()Flush()The first one you have no control over, as it’s automatic. The latter should be an exceptional case, where you want all buffered data written to disk immediately but still want to keep the writer open. The second case–the most important–is what you’re missing.