I'm new to programming and C# is the language I'm learning. My homework instructions are:
Create a program named WritelnventoryRecords that allows you to enter data for items you sell at an online auction site and saves the data to a file. Create an Inventory class that contains fields for item number, description, and asking price.
The code I've written will not write to the text file, it's just blank. What am I missing?
using System;
using System.IO;
class Inventory
{
static void Main()
{
Console.Write("How many items would you like to enter? ");
FileStream file = new FileStream("ItemsSold.txt", FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(file);
int num = Convert.ToInt32(Console.ReadLine());
int itemNum = 0;
string desc;
double price;
for (int count = 0; count < num; ++count)
{
Console.Write("Enter an item number: ");
itemNum = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the item description: ");
desc = Console.ReadLine();
Console.Write("Enter the item price (no dollar sign): ");
price = Convert.ToDouble(Console.ReadLine());
writer.WriteLine(itemNum + "," + desc + "," + price);
}
writer.Close();
file.Close();
Console.ReadLine();
}
}
Thank you for your help.
Your code works on my machine.
If it's still not works, you can try following steps:
When open the file stream, use "FileMode.OpenOrCreate" flag.
Reset the file using "file.SetLength(0);" just after create the file steam.
Flush the buffer before close the file stream: "writer.Flush();"
=== EDIT ===
And yes, like #Preston Guillot posted, check if you are opening the right file.
Related
using System;
using System.IO;
namespace File_Dumping_Script
{
class Program
{
static void Main(string[] args)
{
Random rn = new Random();
string fileName = Convert.ToString(rn.Next(1000));
string path = ("C:\\Users\\taylo\\OneDrive\\Desktop\\FileTesting\\" + fileName);
if (File.Exists(path))
{
fileName = Convert.ToString(rn.Next(1000));
path = ("C:\\Users\\taylo\\OneDrive\\Desktop\\FileTesting\\" + fileName + ".txt");
}
File.CreateText(path);
StreamWriter sw = new StreamWriter(path);
Console.Write("Please enter a seed for the random numbers: ");
int seed = Convert.ToInt32(Console.ReadLine());
int written = 0;
while (written != seed-1)
{
written = rn.Next(seed);
sw.Write(" "+written);
Console.WriteLine(written);
}
sw.Write("\n Process ended.");
Console.WriteLine("Process complete.");
Console.ReadLine();
}
}
}
I want this program to create a file with a random number for a name, and then write a bunch of random numbers to that file. I am currently facing a problem that the File.CreateText(); is using the path, which means that the StreamWriter cannot create an object based off that path. Is there any way I can stop the File.CreateText(); from using the file so the StreamWriter can access it instead?
Also, as a secondary, less important, problem, the files created are not text files, and the way I have tried to fix that with the path = ("C:\\Users\\taylo\\OneDrive\\Desktop\\FileTesting\\" + fileName); doesn't make it a text file and nor does the File.CreateText(); How do I make it a text file instead of a 'file'?
Thank you in advance,
Taylor
I have here a piece of code for my class where I am entering values that are being written into a .txt and .bin file.
My problems are that my .txt file ends up being empty and my .bin file is not writing in binary.
I believe I have written and closed the .bin file and .txt correctly but my inputs are not being stored correctly
Here is my code
static void Main(string[] args)
{
string numberOfStudents, studentName, studentHeight, studentWeight;
int studentInput = 0, height;
bool numberOutput, heightOutput, weightOutput;
double weight;
Console.Write("Enter number of students: ");
numberOfStudents = Console.ReadLine();
numberOutput = int.TryParse(numberOfStudents, out studentInput);
if (numberOutput == true)
{
if (studentInput <= 0)
{
Console.WriteLine("Number of students must be a positive integer (greater than 0)!");
Console.ReadKey();
}
else
{
for (int i = 1; i <= studentInput; i++)
{
Console.Write("Enter student name: ");
studentName = Console.ReadLine();
Console.Write("Enter student height in centimetres: ");
studentHeight = Console.ReadLine();
heightOutput = int.TryParse(studentHeight, out height);
Console.Write("Enter student weight in kilograms: ");
studentWeight = Console.ReadLine();
weightOutput = double.TryParse(studentWeight, out weight);
try
{
StreamWriter outputFile;
outputFile = new StreamWriter("test.txt");
outputFile.Write(numberOfStudents + studentName + studentHeight + studentWeight);
outputFile.Close();
}
catch (System.IO.IOException exc)
{
Console.WriteLine("There was an error!: " + exc.Message);
}
try
{
FileStream outputFile = new FileStream("outFile.bin", FileMode.Create);
BinaryWriter BinFile = new BinaryWriter(outputFile);
BinFile.Write(studentName + " " + studentHeight + " " + studentWeight);
BinFile.Close();
}
catch (System.IO.IOException exc)
{
Console.WriteLine("There was an error!: " + exc.Message);
}
FileStream dataOutput = new FileStream("Database", FileMode.Create);
BinaryWriter databaseFile = new BinaryWriter(dataOutput);
StreamWriter textOutput = new StreamWriter("outText.txt");
databaseFile.Write(studentName + " " + studentHeight + " " + studentWeight);
databaseFile.Close();
textOutput.Close();
}
}
}
Thank you
You're almost there but there are a few issues with the code and it could be tidied up a little.
You are creating 3 files: outFile.bin, outText.txt, and test.txt. No data/text is written to outFile.txt, it is opened then closed a few lines later. Look in test.txt, it will have the last students data (see next point).
You are writing the files in a loop, which is overwriting the data, so only the last users data is being written to the file. Use outputFile = new StreamWriter("test.txt", true) this overload of StreamWriter will allow you to choose to append to the file (true) or overwrite (false).
I'd recommend looking at the using() statement when writing to file or any class that implements IDisposable. For example, when opening the StreamWriter you could do using (var outputFile = new StreamWriter("test.txt", true)) { }. This ensures the streamwriter is closed and disposed by the garbage collector, (For example, you are not closing the dataOutput file stream, if this was in a using(){} block it would automatically be handled for you)
This could be refactored into using just one try {} catch {} block, you do not need a separate try/catch for each time you write to a file.
From the Docs, the BinaryWriter class
Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
So, the binary writer is writing in binary, but the data it's writing are strings. It could easily write int, double, bool, etc.
Here's the code in your try/catch blocks tidied up a bit (this only creates test.txt and outFile.bin):
try
{
// will open or create file in 'append' mode
using (var outputFile = new StreamWriter("test.txt", true))
{
outputFile.Write($"{numberOfStudents}, {studentName}, {studentHeight},{studentWeight}");
outputFile.Write(Environment.NewLine);
}
using (BinaryWriter databaseFile = new BinaryWriter(File.Open("outFile.bin", FileMode.Append)))
{
databaseFile.Write(studentName + " " + studentHeight + " " + studentWeight);
}
}
catch (System.IO.IOException exc)
{
Console.WriteLine("There was an error!: " + exc.Message);
}
I developed a simple program that asks the user if he wants to add a new record to a file or display all the records contained in the file, but I seem to have a problem in writing to the file. The file is created but still nothing is written in it. The reading function works fine since I wrote something in the file to see if it works.
Here is the code...
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace F01
{
class Program
{
static int ID;
static String Name;
static void Main(string[] args)
{
FileStream MyFiler = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader FileReader = new StreamReader(MyFiler);
StreamWriter FileWriter = new StreamWriter(MyFiler);
Console.WriteLine("Please Select One Of The Following Options... ");
Console.WriteLine("1. Enter A New Record In The File.");
Console.WriteLine("2. Read All The Records From The File.");
int Choice = int.Parse(Console.ReadLine());
if (Choice == 1)
{
Console.WriteLine("Enter The ID: ");
ID = int.Parse(Console.ReadLine());
FileWriter.WriteLine(ID);
Console.WriteLine("Enter The Name: ");
Name = Console.ReadLine();
FileWriter.WriteLine(Name);
}
else if (Choice == 2)
{
FileWriter.Close();
String fileText = File.ReadAllText("MyFile.txt");
for (int i = 0; i < fileText.Length; i++)
{
Console.Write(fileText[i]);
}
}
FileReader.Close();
}
}
}
Thanks in advance :)
You're not closing the writer in the only situation in which you're using it - "choice 1". Basically the data is being buffered, and lost when the process exits because you haven't closed the writer.
I would strongly advise you to:
Only open the file when you need to
Use local variables instead of class variables unless you need them in other methods
Use the File static methods to make all of this easier
Use using statements to clean up resources at the end of them (if you need a writer or a stream at all, that is...)
Break your code up into methods for separate operations
Name your variables in camelCase rather than PascalCase
Print your file a line at a time rather than a letter at a time
So for example:
using System;
using System.IO;
class Program
{
const string FileName = "MyFile.txt";
static void Main(string[] args)
{
Console.WriteLine("Please Select One Of The Following Options... ");
Console.WriteLine("1. Enter A New Record In The File.");
Console.WriteLine("2. Read All The Records From The File.");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
AddEntry();
break;
case 2:
ReadFile();
break;
default:
Console.WriteLine("Sorry, that's not a valid option");
break;
}
}
static void AddEntry()
{
Console.WriteLine("Enter the ID:");
int id = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the name:");
string name = Console.ReadLine();
File.AppendAllLines(FileName, new[] { id.ToString(), name });
}
static void ReadFile()
{
foreach (var line in File.ReadLines(FileName))
{
Console.WriteLine(line);
}
}
}
I see your MyFiler which is a FileStream type which is IDisposable type is not wrapped in using statement, nor do you call .Dispose() manually. Same for your readers (which are also disposable types). This can lead to this type of behavior...
Try the follwing:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace F01
{
class Program
{
static int ID;
static String Name;
static void Main(string[] args)
{
using(FileStream MyFiler = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using(StreamReader FileReader = new StreamReader(MyFiler))
{
using(StreamWriter FileWriter = new StreamWriter(MyFiler))
{
Console.WriteLine("Please Select One Of The Following Options... ");
Console.WriteLine("1. Enter A New Record In The File.");
Console.WriteLine("2. Read All The Records From The File.");
int Choice = int.Parse(Console.ReadLine());
if (Choice == 1)
{
Console.WriteLine("Enter The ID: ");
ID = int.Parse(Console.ReadLine());
FileWriter.WriteLine(ID);
Console.WriteLine("Enter The Name: ");
Name = Console.ReadLine();
FileWriter.WriteLine(Name);
}
else if (Choice == 2)
{
FileWriter.Close();
String fileText = File.ReadAllText("MyFile.txt");
for (int i = 0; i < fileText.Length; i++)
{
Console.Write(fileText[i]);
}
}
FileReader.Close();
}
}
}
}
}
}
I need to write an application or Query to export a large amount of PDF's to file and create a delimited text file that shows where the files are and contains the ID of the record.
what I was thinking about doing was using a console application that would write the entry to the text file after exporting the PDF from the DB, that way I would have all the information together when writing the Text File so that I could make sure that all the Data in the Delimited text file was accurate.
at first I was thinking about using a Dataset to do this, but there are going to be more than 50,000 rows of Data. I am not so sure that a DataTable would be any better
I was also looking into using the BCP utility, but from what I was reading the export doesn't give me a PDF File back from the Data, is this true?
I would probably consider myself a beginner, programming something like this.
what should I use for a Data Structure like this? would I use a Cursor, and if so how would I set it up to fit what I am doing?
Update
I am going to try and use the DataSet option, but limit it to 1 days worth of data at a time using a do while loop, so that I can loop through every day from the beginning of the data until today's date. so I will do a days worth of Data and then get rid of the DataSet, then do the next date.
does anyone see anything in my Logic that would cause issues?
when I finally finished researching all the different approaches to the problem, it was really quite simple to code. I did not use BCP at all.
I created Variables for the information that I was extracting that I wanted inside the Text File.
Filename
Date (From SQL Table for the Original Creation Date)
Case Number (internal Identifier for the 3rd party program to link to)
Description (Taken from the SQL Table to describe the document)
Then I put the application to work Writing the Code to PDF one at a time
using (SqlConnection Conn = new SqlConnection(strSQLConn))
{
//open the connection
Conn.Open();
Console.WriteLine("the connection is open");
//Variables needed for looping
DateTime Today = System.DateTime.Now;
DateTime StartDate = Convert.ToDateTime("2008-06-11 00:00:00");
//DateTime StartDate = Today.AddDays(-10);
Console.WriteLine("Converting the Documents from " + StartDate.ToString() + " - TO - " + Today.ToString());
Console.WriteLine("Press Any Key to continue.");
Console.ReadLine();
int RecordCount = 0;
ulong ByteCount = 0;
int i = 1;
foreach (DateTime day in EachDay(StartDate, Today))
{
String strDay = day.ToString();
// Create a SQLCommand to retrieve Data
SqlCommand getRecords = new SqlCommand("spRecapturePDF", Conn);
getRecords.CommandType = CommandType.StoredProcedure;
getRecords.Parameters.Add(new SqlParameter("#OneDay", strDay));
SqlDataReader reader = getRecords.ExecuteReader();
//stuff exporting the binary code to the PDF format
FileStream fs;
BinaryWriter bw;
int buffersize = 100;
byte[] outbyte = new byte[buffersize];
long retval;
long startIndex = 0;
int j = 1;
while (reader.Read())
{
strFileName = reader.GetString(0) + "-" + i + "-" + j;
strDock_no = reader.GetString(0);
dtFiledate = reader.GetDateTime(2);
strDescription = reader.GetString(4);
fs = new FileStream("c:\\FolderName\\" + strFileName + ".pdf", FileMode.OpenOrCreate, FileAccess.Write);
bw = new BinaryWriter(fs);
startIndex = 0;
retval = reader.GetBytes(1,startIndex,outbyte,0,buffersize);
while (retval == buffersize)
{
bw.Write(outbyte);
bw.Flush();
startIndex += buffersize;
retval = reader.GetBytes(1,startIndex,outbyte,0,buffersize);
}
//write the remaining buffer.
bw.Write(outbyte,0,(int)retval);
ByteCount = ByteCount + Convert.ToUInt64(fs.Length);
bw.Flush();
//close the output file
bw.Close();
fs.Close();
//need to write to the Text file here.
TextWriter tw = new StreamWriter(path,true);
tw.WriteLine(strDock_no + "~" + dtFiledate.ToString() + "~" + "c:\\FolderName\\" + strFileName + ".pdf" + "~" + strDescription);
tw.Close();
// increment the J variable for the Next FileName
j++;
RecordCount++;
}
//close the reader and the connection
reader.Close();
i++;
}
Console.WriteLine("Number of Records Processed: " + RecordCount.ToString());
Console.WriteLine("for a Total of : " + ByteCount + " Bytes");
Decimal MByteCount = new Decimal(2);
MByteCount = Convert.ToDecimal(ByteCount) / 1024 / 1024;
Decimal GByteCount = new Decimal(2);
GByteCount = MByteCount / 1024;
Console.WriteLine("Total MBs : " + MByteCount.ToString() + " MB");
Console.WriteLine("Total GBs : " + GByteCount.ToString() + " GB");
Console.WriteLine("Press Enter to Continue ...");
Console.ReadLine();
}
this Code was enclosed in a foreach statement that went day by day, from a starting date to an end date. inside that foreach statement the Application called a stored procedure that was given the specified day to call the records that were entered that day.
variables i and j were created because I needed to have a unique Filename even if I had the same Case Number. i represented the day (because I went day by day in my select statement) and j represented the record number for that day from the select statement.
the foreach and the while loops were enclosed in a using(conn) so that no matter what the connection would be closed finally.
at the end of the while loop I wrote to the Text File. the Text file was created outside of all the loops so that I could just append the file rather than overwrite it. that code is:
string path = #"c:\\FolderName\\TextFile.txt";
if (!File.Exists(path))
{
TextWriter tw = new StreamWriter(path, false);
tw.WriteLine("Dock_No~Date~FileName(Location)~Description");
tw.Close();
}
I hope that this helps someone else. I left out all the Console.Writeline and Console.ReadLine code that wasn't necessary to the functionality i was looking for. I had added some code also that would count the bytes that were written and some code to count the records processed. this is just fun stuff to know, I need to clean up the Fun stuff at the end.
these are the Guts of what it took to accomplish a mass Extract of PDFs from a Blob Field in SQL Server, minus some Connection Mumbo Jumbo
Foreach Day Set up
this is the Code that I used to make the foreach work the way that I wanted it to.
static public IEnumerable<DateTime> EachDay(DateTime Startdate, DateTime EndDate)
{
for (var day = Startdate.Date; day.Date <= EndDate.Date; day = day.AddDays(1))
yield return day;
}
Using Seek Method to read a specific part of a text but it fails.
I have two classes "allmethods.cs" and "caller.cs"
There are two methods in "allmethods.cs" which are "WritingMethod" and "SeekReader"
The program should writes in a text file and read data using seek method in order to read certain part in the text file.
The programs writes smoothly in the text file but it doesn't read anything when calling "SeekReader" which is the seek method.
My Code:
public class allmethods
{
private static string Name;
private static int ID;
private static int Age;
private static string Email;
private static string output;
public static void WritingMethod()
{
int count = 0;
while (count < 10)
{
Console.Write(" Enter your Name: ");
Name = Console.ReadLine();
Console.Write(" Enter your ID: ");
ID = int.Parse(Console.ReadLine());
Console.Write(" Enter your Age: ");
Age = int.Parse(Console.ReadLine());
Console.Write(" Enter your E-mail: ");
Email = Console.ReadLine();
StreamWriter Sw = new StreamWriter("fileone.txt", true);
string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
+ Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);
Console.WriteLine(output);
Sw.WriteLine(output + Environment.NewLine);
Console.ReadLine();
Sw.Close();
count++;
}
}
public static void SeekReader()
{
FileStream FS=new FileStream("fileone.txt",FileMode.Open,FileAccess.Read);
StreamReader SR = new StreamReader(FS);
SR.BaseStream.Seek(2, SeekOrigin.Begin);
FS.Close();
SR.Close();
}
}
I failed to identify the error. Any suggestions?
Thanks in Advance.
You can use File.ReadAllText([FilePah]) to read the file.
public static void SeekReader()
{
FileStream fsr = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read);
StreamReader Sr = new StreamReader(fsr);
string line = string.Empty;
var ctr = 0;
while(ctr < 3){
line = Sr.ReadLine();
ctr++;
}
Console.WriteLine(line);
Sr.Close();
fsr.Close();
}