Reputation: 19
Heyy, so I'm having a little trouble with a program I'm working on for class. I'm thinking that the error I'm making is small, but I just can't seem to find it. It seems as though my sInsults array is not getting saved properly, or that it is not being passed the strings correctly. Someone please point out my obvious mistake lol. And don't judge on the hilarious insults, they are specified by my teacher xD
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utilities;
using System.IO;
namespace ICA27
{
class Program
{
static void Main(string[] args)
{
string[] sNames = { "Al ", "John ", "JD ", "Bill ", "Ross " };
string[] sVerbs = { "talks to ", "licks ", "runs ", "flushes ", "uses " };
string[] sObjects = { "safeway carts.", "Microsoft.", "old mops.", "dead cows.", "Vista." };
string[] sInsults = MakeInsults(sNames, sVerbs, sObjects);
SaveInsults(sInsults);
}
static string[] MakeInsults(string[] sNames, string[] sVerbs, string[] sObjects)
{
string sString = "How many insults do you want to make? ";
int iInput = 0;
CUtilities.GetValue(out iInput, sString, 5, 100);
string[] sInsults = new string[iInput];
Random rNum = new Random();
for (int i = 0; i< iInput; i++)
{
sInsults[i] = sNames[rNum.Next(sNames.Length)] + sVerbs[rNum.Next(sVerbs.Length)] + sObjects[rNum.Next(sObjects.Length)];
}
Console.WriteLine("Array of insults have been created!");
return sInsults;
}
static void SaveInsults(string[] sInsults)
{
Console.Write("What would you like the file to be named? ");
string sName = Console.ReadLine();
StreamWriter swName;
Console.Write("Would you like to append the file? ");
string sAnswer = Console.ReadLine();
sAnswer = sAnswer.ToUpper();
if ((sAnswer == "YES")||(sAnswer == "Y"))
{
swName = new StreamWriter(sName, true);
}
else
{
swName = new StreamWriter(sName);
}
for (int iI = 0; iI < sInsults.Length; iI++)
swName.WriteLine(sInsults[iI]);
}
}
}
Upvotes: 2
Views: 101
Reputation: 26209
Solution 1 : You need to close your StreamWriter
instance variable swName
.
Try This:
for (int iI = 0; iI < sInsults.Length; iI++)
swName.WriteLine(sInsults[iI]);
swName.Close(); //add this statement
Solution 2:
I Would suggest you to enclose the StreamWriter
Object declaration within using{}
block to ensure that your objects gets disposed properly.
Try This:
using(StreamWriter swName = new StreamWriter(sName, true))
{
for (int iI = 0; iI < sInsults.Length; iI++)
swName.WriteLine(sInsults[iI]);
}
Solution 3: You can still use using block by just checking the if condition.
Try This:
bool IsAppend = false;
if ((sAnswer == "YES")||(sAnswer == "Y"))
{
IsAppend = true;
}
using(StreamWriter swName = new StreamWriter(sName, IsAppend))
{
for (int iI = 0; iI < sInsults.Length; iI++)
swName.WriteLine(sInsults[iI]);
}
Upvotes: 4