This question already has an answer here:
No StreamReader constructor accepting a string
(1 answer)
Closed 5 years ago.
I have a problem that requires me to calculate synthetic student marks from a text file. It gives me the weights of the marks in the first row, the number of students to evaluate in the next row, and then the next rows are the students' marks. This pattern repeats through the file without major separation.
For clarity, the text file and problem are here:
I've tried making a new object with streamreader using the following code:
using (StreamReader sr = new StreamReader("DATA10.txt")) {
blahblahblah;
}
DATA10.txt is in the same folder as the program.
But I get "Cannot convert from 'string' to 'System.IO.Stream'", even though in the examples on MSDN and everywhere else use that exact code just fine. What am I doing wrong?
Eventually what I'll be doing is taking the value from the second line and using streamreader to read that amount of lines. Then repeating the whole process on the next set of data.
I really don't think it's a duplicate of that question, and the answers here are expressed in an easier to understand way.
StreamReader is suppose to take in a Stream as its parameter can also take in a Stream as a parameter and you will also have to specify the FileMode.
Instead, try something like this:
public static void Main()
{
string path = #"c:\PathToFile\DATA10.txt";
try
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
//blahblah
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
MSDN Reference
You must also set the "Copy to output directory" property of "DATA10.txt" in Solution Explorer to "Copy Always"
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _07___ReadTextFileWhile
{
class Program
{
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("DATA10.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
Console.WriteLine(line);
}
myReader.Close();
Console.ReadKey();
}
}
}
Related
This question already has answers here:
Write List<KeyValuePair<string, List<string>>> to text file?
(3 answers)
How can I write the values in a List to a text file?
(2 answers)
Writing List<String> contents to text file after deleting string
(3 answers)
Closed 3 years ago.
I´m currently trying to improve my c# skills and want to make a check-in system for workers. I want to save the timestamps in a text file and add every new stamp in the same personal .txt file.
My problem is not making it work, my problem is when I write out my list the line System.Collections.Generic.List1[System.String]` is added for every text I add. Please Help me solve this problem.
I don´t really know how to get rid of the System.Collections.Generic.List1[System.String]` part
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Provar_på_IO_File_system
{
class Program
{
static void Main(string[] args)
{
string workerName = "Albert Einstien";
string date = "2019-10-17";
string time = "14.29";
if (File.Exists(workerName + ".txt"))
{
string line;
StreamReader sr = new StreamReader(workerName + ".txt");
List<string> readLines = new List<string>();
line = sr.ReadLine();
while (line != null)
{
readLines.Add(line);
line = sr.ReadLine();
}
sr.Close();
using (StreamWriter sw = File.AppendText(workerName + ".txt"))
{
sw.WriteLine(readLines);
sw.WriteLine("HELLLLLLLLLOOOOOOOOOOOOOOOOOOOOOOOO");
sw.Close();
}
}
else
{
FileStream fs = new FileStream(workerName + ".txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(date + "\t" + time + "\t" + workerName);
sw.Close();
fs.Close();
}
}
}
}
So the result I'm planning to get from this is to see if just that worker has a text file. If it has none it will create a personal file for that person and add the timestamps for him. Otherwise, if the file already, exists (he have already check-in at least once) the program will read the .txt file, save every line into a list and after that write everything that stod in the file when the system opened it but also add the new timestamp.
Everything works as I like but it doesn't only add the timestamp, the program adds the line System.Collections.Generic.List1[System.String]" and then the timestamps.
You would need to loop through the List readLines.
var fileName = string.Format("{0}.txt", workerName)
using (StreamWriter sw = File.AppendText(fileName)) {
foreach(string line in readLines) {
sw.WriteLine(line);
}
}
I am working on StreamReader in C#. I am getting the error
"The type or namespace name "StreamReader" could not be found"
I have no idea what I am doing wrong.
using System.IO;
using System;
class Perfect
{
static void Main()
{
string filename = #"marks.cvs";
StreamReader sr = new StreamReader(filename);
string line = sr.ReadLine();
Console.WriteLine(line);
sr.Close();
}
}
StreamReader is in the System.IO namespace. You can add this namespace at the top of your code by doing the following-
using System.IO;
Alternatively, you could fully qualify all instances of StreamReader like so-
System.IO.StreamReader sr = new System.IO.StreamReader(filename);
But this may get a little tedious, especially if you end up using other objects in System.IO. Therefore I would recommend going with the former.
More on namespaces and the using directive-
https://msdn.microsoft.com/en-us/library/0d941h9d.aspx
https://msdn.microsoft.com/en-us/library/sf0df423.aspx
StreamReader requires a namespace which you are missing. Add these two at top of the .cs file.
using System;
using System.IO;
StreamReader sr = new StreamReader(filename);
Its always a best-practice to add namespace at top of the file. However, you can add like this System.IO.StreamReader mentioned by #iliketocode.
System.IO.StreamReader sr = new System.IO.StreamReader(filename);
I wasn't going to post the answer, but just had another good programming practice to point out.
Firstly, to answer your question, if you want to use StreamReader you need to tell the compiler where to find it. Adding a using System.IO.StreamReader; at the top of your .cs file would do that.
Secondly, when using streams, it is better to wrap your interaction with the stream in a using(){}. The way I would write your code would be:
using System;
using System.IO;
using System.IO.StreamReader;
class Perfect
{
static void Main()
{
const string filename = #"marks.cvs";
using (var sr = new StreamReader(filename))
{
string line = sr.ReadLine();
Console.WriteLine(line);
}
}
}
In the code included below, I am able to write the contents of the string 'fullname' to a text file in the specified directory when using the following statement:
System.IO.File.WriteAllText(path, fullname);
However, if I write the string path to a FileStream object (withe arguments specified), and then pass that FileStream object as an argument to the StreamWriter object, the file is created, but no contents are written.
First attempt: Comment out System.IO.File.WriteAllText(path, fullname); and use the three lines above it. This creates the file but no contents are written into the file.
Second attempt: Un-comment the System.IO.File.WriteAllText(path, fullname); statement and comment the three lines above it. This executes as desired.
Here is the full block of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
class Program
{
static void Main(string[] args)
{
// Use the Split() method of the String Class
string fullname = " Robert Gordon Orr ";
fullname = fullname.Trim();
string[] splitNameArray = fullname.Split(' ');
Console.WriteLine("First Name is: {0}", splitNameArray[0]);
Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
Console.WriteLine("Full name is: {0}", fullname);
string path = #"C:\Programming\C#\C# Practice Folder\Console Applications\FileInputOutput\textfile.txt";
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
StreamWriter toFile = new StreamWriter(fs);
toFile.Write(fullname);
//System.IO.File.WriteAllText(path, fullname);`enter code here`
Console.ReadLine();
}
}
}
As others have said: streams must be flushed in .NET in order for them to write to disk. This can be done manually, however I would simply change your code to have using statements on your streams:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
class Program
{
static void Main(string[] args)
{
// Use the Split() method of the String Class
string fullname = " Robert Gordon Orr ";
fullname = fullname.Trim();
string[] splitNameArray = fullname.Split(' ');
Console.WriteLine("First Name is: {0}", splitNameArray[0]);
Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
Console.WriteLine("Full name is: {0}", fullname);
string path = #"C:\textfile.txt";
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
using (StreamWriter toFile = new StreamWriter(fs))
{
toFile.Write(fullname);
}
}
//System.IO.File.WriteAllText(path, fullname);`enter code here`
Console.ReadLine();
}
}
}
Calling Dispose() on a stream (as using implicitly does), causes the stream to be flushed and closed at the end of the using block.
I think you are just forgetting to flush your file stream:
fs.Flush();
This is needed because according to msdn, this is what makes the FileStream to actually write the buffer to the file.
Flush: Clears buffers for this stream and causes any buffered data to be written to the file. (Overrides Stream.Flush().)
Regards.
From MSDN on StreamWriter
You must call Close to ensure that all data is correctly written out to the underlying stream.
So the problem here is mainly that, since you don't actually close the StreamWriter, the data gets backed up but doesn't push to the file, even though the FileStream immediately created the file in its constructor. Never ever forget to close your stream, as failing to do so could lead to major problems down the line.
This question already has answers here:
How to copy a file while it is being used by another process
(7 answers)
Closed 9 years ago.
Is it possible to copy a pst file using c# with outlook open?
Here is the code i have got already but it still gives me the error :The process cannot access the file 'filepath' because it is being used by another process.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace outlookPSTCopy
{
class Program
{
static void Main(string[] args)
{
string done = "the file is done copying";//done massage
string copyFrom = args[0];
string copyTo = args[1];
Console.WriteLine(copyTo);
Console.ReadLine();
try
{
//start of test
using (var inputFile = File.Open(copyFrom, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
using (var outputFile = new FileStream(copyTo, FileMode.Create))
{
var buffer = new byte[0x10000];
int bytes;
while ((bytes = inputFile.Read(buffer, 0, buffer.Length)) > 0)
{
outputFile.Write(buffer, 0, bytes);
}
}
}
//end of test
//System.IO.File.Copy(copyFrom, copyTo, true);
}
catch (Exception copyError)
{
Console.WriteLine("{0} Second exception caught.", copyError);
}
Console.WriteLine("{0} ", done);
Console.ReadLine();
}
}
}
Thank you for your help!
To create a copy of a file that is locked by another process on Windows, the simplest (and probably only) solution is to use the Volume Shadow Copy Service (VSS).
The Volume Shadow Copy Service is complex and difficult to call from managed code. Fortunately, some fine chaps have created a .NET class library for doing just this. Check out the Alpha VSS project on CodePlex: http://alphavss.codeplex.com.
Well, first of all my code :
protected void Button2_Click1(object sender, EventArgs e)
{
string batname = edit.SelectedValue;
StreamWriter sw = new StreamWriter("D:\\MPSite-Serv\\bats\\" + batname);
string theedit = batedit.Text;
sw.WriteLine(theedit);
sw.Flush();
}
When I click on button2 and try to write all of the text into the bat file, I get this result the bat file contains:
System.Web.UI.WebControls.TextBox
Why is that?
I am using all of the following statements, if it helps:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Diagnostics;
You are getting the type name of the textbox, which leads me to believe that your code rather looks something like:
sw.WriteLine(batedit);
I.e. you are sending the textbox object itself to be written to the file instead of the contents of its Text property. This will implicitly call the ToString method, which by default returns the type name of the object.
Also, you are not closing the StreamWriter properly, which might cause problems when you want to use it. You should call the Close method, and you don't have to call Flush before closing the StreamWriter. Alternatively you can put the StreamWriter in a using block, which would dispose it automatically, which will close it.
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx#Y2863
The problem is simple: sw.writeline expects a string. You are sending it a text object which gets turned into the aformentioned .ToString(); which means your line gets translated, loosely, into
sw.WriteLine(theedit.ToString());
if you look at the documentation for WebControls.TextBox... scroll down the list to the Method ToString()
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.aspx
What you need to do... is give it one string at a time (although I assume you could just give it the raw string from the textbox):
using System.IO;
namespace String_Writer
{
class Program
{
static void Main(string[] args)
{
string batname = "test.txt";
string theedit = "Testing one two three four\n\nfive six seven eight.";
using(StreamWriter sw = File.CreateText("C:\\Users\\Kriis\\Desktop\\" + batname))
{
using (StringReader reader = new StringReader(theedit))
{
string line = string.Empty;
do
{
line = reader.ReadLine();
if (line != null)
{
sw.WriteLine(line);
}
} while (line != null);
}
}
}
}
}