i have created a marksheet program in c# 2005, its working fine it is taking input and showing the output by using the below code. now if i want that the output of this program is also copied in a new file located in my C or any drive. what should i do? i tried IO.StreamWriter but its not working.
using(System.IO.TextWriter writer = System.IO.File.CreateText(#"C:\1.txt"))
{
Console.WriteLine("\t\tMarksheet - Prislogix Public School");
Console.Write("\n\nStudent Name : " + name);
Console.Write("\nClass : " + cls);
Console.Write("\nRoll Number : " + roll);
Console.Write("\n\nSubject\t\tObtained Marks\t\tTotal Marks");
Console.Write("\n\nChemistry\t\t" + chem + "\t\t75");
Console.Write("\nEnglish\t\t\t" + eng + "\t\t100");
Console.Write("\nCalculus\t\t\t" + urd + "\t\t100");
Console.Write("\nDiscrete\t\t\t" + sin + "\t\t75");
Console.Write("\nMathematics\t\t" + mat + "\t\t100");
Console.Write("\nPhysics\t\t\t" + phy + "\t\t75");
Console.Write("\nComputer\t\t" + comp + "\t\t100");
Console.Write("\nMethods\t\t" + isl + "\t\t50");
float tot = chem + eng + urd + sin + mat + phy + comp + isl;
Console.Write("\n\n\t\t\tTotal Obtained Marks : " + tot + "\tOut Of 625");
float per;
per = (tot / 625) * 100;
Console.Write("\n\t\t\tPercentage : " + per + "%");
if (per < 49 && per > 40)
{
Console.Write("\n\t\t\tFAILED!");
}
if (per <= 59 && per >= 50)
{
Console.Write("\n\t\t\tGrade : C");
}
if (per <= 69 && per >= 60)
{
Console.Write("\n\t\t\tGrade : B");
}
if (per <= 79 && per >= 70)
{
Console.Write("\n\t\t\tGrade : A");
}
if (per <= 89 && per >= 80)
{
Console.Write("\n\t\t\tGrade : A+");
}
if (per <= 100 && per >= 90)
{
Console.Write("\n\t\t\tGrade : A-ONE");
}
}
}
Console.ReadLine();
StreamWriter does work. It's a shame you haven't shown us your attempt at using it.
The simplest way of creating a StreamWriter to write to a file is to use File.CreateText. Then you should be able to use StreamWriter.Write in the same way as Console.Write. Don't forget to use a using statement:
using (TextWriter writer = File.CreateText("..."))
{
// Write stuff here
}
That makes sure the writer will be disposed at the end of the using statement, which will flush and close the file.
If you want to write to both the console and the file, you may want a "tee" TextWriter which writes to two outputs... or you could just look at the file after running the program.
One thing to note: in Windows, the normal line ending is \r\n rather than just \n. If the problem was just that all the output looked like it was on one line in Notepad, that's probably the issue. Consider using WriteLine instead of Write, to write out the platform default line terminator at the end of the line.
If all of this fails, please tell us what's going wrong with rather more detail than "it's not working".
Change all calls to Console.Write so that they write to a StringBuilder instance instead. After the printing is done you can do the following:
Console.Write(stringBuilder.ToString());
System.IO.File.WriteAllText("your path here", stringBuilder.ToString());
This will probably be the easiest fix. It will still write the output to the Console, but it will also write to the file you want.
Related
Hi guys I need help solving a c# problem. This is the code being run as you can see it repeats 1bottles and 1 bottle on the picture I would like to know how to remove the "1 bottles on the wall take one down" and keep "1 bottle on the wall" please help
class Program
{
static void Main(string[] args)
{
string strBottles = "bottles";
int bottles = 100;
while (bottles <= 100)
{
Console.WriteLine(bottles + strBottles + " on the wall" + " take one down");
if(bottles == 1)
{
strBottles = "bottle";
Console.WriteLine(bottles + strBottles + " on the wall");
break;
}
bottles--;
}
}
}
You need to check the value before the first message printing, add an if check like so,
if(bottles>1)
Console.WriteLine(bottles + strBottles + " on the wall" + " take one down");
Choosing a possible infinite do/while with a break condition that can or cannot be fullfilled is a bad idea
I will try this aproach:
string strBottle = "bottle";
int iBottles = 100;
for (int bottles = iBottles; bottles >=1; bottles--)
{
Console.WriteLine(bottles + strBottle + (bottles>1?"s":"") +" on the wall" + (bottles > 1 ? " take one down":""));
}
Think about what the code is doing when bottles == 1.
First it hits this line
Console.WriteLine(bottles + strBottles + " on the wall" + " take one down");
then it enters the if statement:
if(bottles == 1)
{
strBottles = "bottle";
Console.WriteLine(bottles + strBottles + " on the wall");
break;
}
If you want only the "1bottle on the wall", then the if statement needs to come first:
while (bottles > 0)
{
if(bottles == 1)
{
Console.WriteLine($"{bottles} bottle on the wall");
break;
}
Console.WriteLine($"{bottles} bottles on the wall take one down");
bottles--;
}
Other improvements:
while (bottles <= 100) - bottles starts at 100 and decreases so this statement will always be true. If you changed the initial number of bottles to int bottles = 101 the code wouldn't execute the while loop in your version. You never want it to go below 1 so the condition should be while (bottles > 0)
You don't really need the string strBottles, it's redundant and can be removed
If you're using C# 6.0 or above take a look at string interpolation. It provides a more readable way to format strings with expressions: $"{bottles} bottles on the wall"
I'm currently working on a thesis for high school in Germany. My topic is to figure out how we can make traffic intersections more efficient through automation. For this, I'm building a small simulation in Unity3D and right now I'm working on the script and settings for the car. In order to compare multiple settings, I would like to export some data in order to analyze it with NumPy and Matplotlib. But to do so I have to export the data out of Unity.
Right now the car is driving through some waypoints and I would like to get the time when the car is reaching those points.
So now I only have to save them outside of Unity in a format so I could easily import it inside of my jupyter notebook in order to analyze it.
So how would I do this? I know this might be a simple question but most guides are for game objects or characters. So they've saved it for a different purpose.
Update:
Thanks for the help. I got it fixed and now it is writing into a txt file.
Code
Is there a possibility that Unity is creating a new txt file every single time when I run the script. I'm not quite sure if this is even possible at all since I'm technical starting the whole system again and there is no information from last time. As an example that now it's called data1.txt and the next time I'm starting the code it is now saving it into data2.txt.
This is the current output just for some reference.
Data.txt
void FixedUpdate()
{
speed = Engine.currentSpeed;
time = Time.time;
node = Engine.node;
xPos = Auto.transform.position.x;
zPos = Auto.transform.position.z;
if (IsRunning == true)
{
StartCoroutine(Wait());
}
}
public IEnumerator Wait()
{
IsRunning = false;
yield return new WaitForSeconds(WaitTimer);
Output();
IsRunning = true;
}
void Output()
{
print("[" + motorTorque + "," + maxSpeed + "," + steerAngle + "," + node + "," + time + "," + speed + "," + xPos + "," + zPos + "]");
StreamWriter writer = File.AppendText(#"C:\Users\kaykl\Documents\Schule\Info\Data\CarControle\data.txt");
writer.WriteLine("[" + motorTorque + "," + maxSpeed + "," + steerAngle + "," + node + "," + time + "," + speed + "," + xPos + "," + zPos + "]");
writer.Close();
if (IsRunning == true)
{
StartCoroutine(Wait());
}
if (node == 0 && cancel == false)
{
cancel = true;
}
else if (node == 0 && cancel == true)
{
writer.Close();
}
}
An easy way will be save what you need to a file:
https://forum.unity3d.com/threads/how-to-write-a-file.8864/
And for coding a different file every time, just include a time-stamp in the filename.
And alternative will be to use Unity Analytics:
https://unity3d.com/unity/features/analytics
It comes with some nice graphs that could be useful when presenting your thesis.
Good luck!
I'm trying to read out the contents off a Setting inside my Application. Below is the code i'm having troubles with:
private bool checkGrid()
{
string playlists = Spotify_Extender.Properties.Settings.Default.Playlists;
MessageBox.Show(playlists);
string[] split1;
if (playlists.Contains(";"))
{
MessageBox.Show("Multiple Links");
split1 = playlists.Split(';');
}
else
{
MessageBox.Show("One Link");
split1 = new string[1];
split1[0] = playlists;
}
MessageBox.Show("Array Length: " + split1.Length);
int lines = 0;
for (int i = 0; i < split1.Length; i++)
{
MessageBox.Show("Check #" + i + " - " + split1[i] + " - Length: " + split1[i].Length);
if (split1[i].Length >= 22)
{
MessageBox.Show(i + " - " + split1[1]);
lines++;
}
}
int rows = this.playlistGrid.Rows.Count;
MessageBox.Show(lines + "");
if (rows == lines)
return true;
return false;
}
The code should be easy to understand and it should work as far as i am aware, but it doesn't. I entered this in my Setting:
If i run the program now, my first MessageBox prints out exactly what i entered, the second one prints out "One Link" and the third prints "Array Length: 1". Now we get to the part i'm having troubles with. The next Message is this:
So the length of the text is 22 as displayed in the MessageBox, but down below this statement isn't true:
if (split1[i].Length >= 22)
I'm really confused by this and it also does this when i check this:
if (split1[i] != "")
Any help is appreciated, because i don't know what to do, since my code should be fine. Thanks for your time!
You should have split[i] and not split[1]
I have a whole bunch of .wav files which are to be concatenated by a program , based on a list of file names supplied to it.
The program kept turning legible audio files into garbage .. upon investigation using audacity I realised that the files have all been recorded on different devices some in mono format , some in stereo, at different sampling rates etc.
To be able to convert these files into the required common sampling rate- all in stereo etc, I need to run a few batch conversions in audacity.
For this I need to files separated out into groups with same sampling rate and same number of tracks etc.
I wrote a utility program in c# that can scan a folder that has all these files and give me a comma separated txt file with the file name and the formatting info.
I am reading the file stream into a bytearray , but while interpreting the formatting info- I think the program is somehow adding extra 0s at the end of each format info,
What is going wrong ? Any help is appreciated.
Relevant Code below -
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#pathString))
{
fileLine += "[Resource Name ], [File Size], [Format Chunk Size], [isPCM ? ], [Num of Channels], [Sample Rate], [(Sample Rate * BitsPerSample * Channels) / 8],[BitsPerSample * Channels) / 8], [Bits PerSample], [Data Size ]" + Environment.NewLine;
file.WriteLine(fileLine);
fileLine = "";
for (i = 0; i < FileNames.Length; i++)
{
string fname = "";
fname = FileNames[i];
fileLine += "'" + fname + "',";
Byte[] resBytesArr = ByteArrFromFileStream(FileNames[i]);
if (resBytesArr.Length > 44)
{
// file size
fileLine += "," + resBytesArr[4] + resBytesArr[5] + resBytesArr[6] + resBytesArr[7] ;
// fmt size
fileLine += "," + resBytesArr[16] + resBytesArr[17] + resBytesArr[18] + resBytesArr[19] ;
// format ? 1 for PCM
fileLine += "," + resBytesArr[20] + resBytesArr[21];
// num of channels
fileLine += "," + resBytesArr[22] + resBytesArr[23] ;
// sample rate
fileLine += "," + resBytesArr[24] + resBytesArr[25] + resBytesArr[26] + resBytesArr[27] ;
//(Sample Rate * BitsPerSample * Channels) / 8
fileLine += "," + resBytesArr[28] + resBytesArr[29] + resBytesArr[30] + resBytesArr[31] ;
//(BitsPerSample * Channels) / 8.1 - 8 bit mono2 - 8 bit stereo/16 bit mono4 - 16 bit stereo
fileLine += "," + resBytesArr[32] + resBytesArr[33] ;
//Bits per sample
fileLine += "," + resBytesArr[34] + resBytesArr[35] ;
// data size
fileLine += "," + resBytesArr[40] + resBytesArr[41] + resBytesArr[42] + resBytesArr[43] ;
// end of info for one resource, move to next
fileLine += Environment.NewLine;
file.WriteLine(fileLine);
fileLine = "";
file.WriteLine(".....done." + Environment.NewLine);
}
else
{
file.WriteLine("Byte Array seems invalid for " + fname + Environment.NewLine);
}
}
}
Remember that array members (including byte[]) are automatically initialized to the default initial value for the array type. Byte[] arrays are initialized to 0x0. Without really seeing what's going on in:
ByteArrFromFileStream(...)
I'd have to guess, and my guess is that on some of your files, the actual application that originally encoded the binary stream created a standard block-sized malloc() memory allocation buffer. When the actual encoding of the stream was completed, the length of the stream fell several bytes short of the last memory allocation. So when the file is written to disk, a bunch of 0x0's get written out with it.
As a side note, when using any of the 'Stream' types be sure to be careful about who and what closes down the stream, for further reading I recommend a perusal of this article: http://msdn.microsoft.com/en-us/library/bb985010.aspx
I have written a console application that in itself is working as I would like it to. It's main output works great in console. But the results inside the loop I want written to a text file. I have used StreamWriter to attempt this and although I receive no errors on compilation or running, the file in my C: drive remains blank. Can anyone spot any stupid or quick things I have missed?
If you can help, thank you in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test2
{
class Program
{
static void Main(string[] args)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\Test.txt");
double z = 0;
double x = 1;
double y = 1;
Console.WriteLine("How many lines should be written to the file?");
Console.WriteLine();
z = double.Parse(System.Console.ReadLine());
Console.WriteLine("Writing " + z + "lines to file!");
Console.WriteLine();
while (z > 0)
{
y = Math.Pow(x, 2);
Console.WriteLine(x + ", " + y*10);
file.WriteLine(x + ", " + y*10);
z = z - 1;
x = x + 1;
}
Console.WriteLine();
Console.WriteLine("**Generation Complete**");
Console.WriteLine();
Console.WriteLine("-------------------------------");
Console.WriteLine();
Console.WriteLine("**Writing to file successful**");
Console.WriteLine();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
file.Close();
}
}
}
I've had issues similar to this before. If I recall correctly, the solution came down to wrapping the StreamWriter in a using block, rather than creating it and then trying to close it, e.g.
static void Main(string[] args)
{
using (var file = new System.IO.StreamWriter("c:\\Test.txt"))
{
double z = 0;
double x = 1;
double y = 1;
Console.WriteLine("How many lines should be written to the file?");
Console.WriteLine();
z = double.Parse(System.Console.ReadLine());
Console.WriteLine("Writing " + z + "lines to file!");
Console.WriteLine();
while (z > 0)
{
y = Math.Pow(x, 2);
Console.WriteLine(x + ", " + y*10);
file.WriteLine(x + ", " + y*10);
z = z - 1;
x = x + 1;
}
Console.WriteLine();
Console.WriteLine("**Generation Complete**");
Console.WriteLine();
Console.WriteLine("-------------------------------");
Console.WriteLine();
Console.WriteLine("**Writing to file successful**");
Console.WriteLine();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
Use the using statament for everything that implements IDisposable like the StreamWriter. This will ensure that unmanaged resources are disposed (even on error). It'll also flush the stream if it's AutoFlush property is false(default).
using(var file = new System.IO.StreamWriter("c:\\Test.txt"))
{
// ...
file.WriteLine(x + ", " + y*10);
// rest of code here ...
}
Does Stream.Dispose always call Stream.Close (and Stream.Flush)
When I run that code, I see an exception:
Unhandled Exception: System.UnauthorizedAccessException:
Access to the path 'c:\Test.txt' is denied.
It's not clear how you're running this, but if it's configured as a console app and you run it from a console window so you'll definitely see any exceptions, I suspect you'll see the same thing.
Try changing it to write to somewhere you definitely have access to - and also try to work out why you didn't see the exception before.
Additionally it would definitely be better to use a using statement as other answers have shown - but that wouldn't explain a clean run (no exceptions) without the file being created.