I am unable to create new .txt file using StreamWriter Class - c#

Here is my code...
string path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Music", "stream.txt");
StreamWriter sw = new StreamWriter("stream.txt");
sw.WriteLine("i am stream");
sw.Close();

You almost had the solution there:
string path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"),"Music", "stream.txt");
StreamWriter sw = new StreamWriter(path);
sw.WriteLine("i am stream");
sw.Close();
You just had to use the path variable you created :)
After execution remember to look in the Music folder for the stream.txt file

Check This one:-
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
Reference

Related

Deleting text from file

How can I delete text from text file? For example I have some text and every time I would change the text box text in a file will change. This is what I mean:
StreamWriter = sw;
StreamReader = sr;
string path = "file.txt";
string text = txtText.Text;
if(!File.Exists(path))
{
sw = File.CreateText(path)
}
else
{
sw = new StreamWriter(path, true)
}
//here I want to delete previous line
sw.WriteLine(text)
sw.Close()
you have to replace
sw = new StreamWriter(path, true)
with
sw = new StreamWriter(path, false)
since boolean parameter defines append new text or not
and I recommend to use using to dispose the resource after using
if (!File.Exists(path))
{
sw = File.CreateText(path);
}
else
{
sw = new StreamWriter(path, false);
}
using (sw)
{
sw.WriteLine(text);
};

Could not find a part of the path (Write file html)

I need to create html file and save to drive C:/TMP after i public it error
Could not find a part of the path 'C:\TMP\test.html'
I have the following code
string fileName = #"C:\\TMP\\test.html";
using (FileStream fs = File.Create(fileName))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
w.WriteLine("<title>PChart</title>");
w.WriteLine("</p>");
w.WriteLine("</body>");
w.WriteLine("</html>");
}
}
Are you sure the directory exists ? Put Directory.CreateDirectory in our code:
string fileName = #"C:\\TMP\\BlaBla\\test.html";
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
using (FileStream fs = File.Create(fileName))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
w.WriteLine("<title>PChart</title>");
w.WriteLine("</p>");
w.WriteLine("</body>");
w.WriteLine("</html>");
}
}
I tested, for me it works
Hi pls try using below code. If there is no file It will create. But path should be correct.
string path = #"D:\\TMP\\test.html";
using (StreamWriter w = System.IO.File.AppendText(path))
{
w.WriteLine("<!DOCTYPE html>");
w.WriteLine("<html>");
w.WriteLine("<head>");
w.WriteLine("<title>PChart</title>");
w.WriteLine("</p>");
w.WriteLine("</body>");
w.WriteLine("</html>");
}

C# how to read 2 files using Stream and response both as 1

I need to read 2 files and somehow combine them and response them both as 1.
I don't want to create a new file containing both files text.
This is my code to response my main file,
FileStream fs = File.OpenRead(string.Format("{0}/neg.acc",
Settings.Default.negSourceLocation));
using (StreamReader sr = new StreamReader(fs))
{
string jsContent = sr.ReadToEnd();
context.Response.Write(jsContent);
}
I need my 2nd file to be read right after the main is done.
An easy way to explain it:
lets assume main file contains : "hello"
and 2nd file contains: "what a beautiful day"
my response should be:
"hello"
"what a beautiful day"
Thanks in advance
FileStream is also a disposable object like StreamReader. Best to wrap that in a using statement too. Also to make the code a little more reusable, place the code to read the text file into its own method, something like:
public static string CombineFilesText(string mainPath, string clientPath)
{
string returnText = ReadTextFile(mainPath);
returnText += ReadTextFile(clientPath);
return returnText;
}
private static string ReadTextFile(string filePath)
{
using (FileStream stream = File.OpenRead(filePath))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string File1 = #"c:\temp\MyTest1.txt";
string File2 = #"c:\temp\MyTest2.txt";
if (File.Exists(File1))
{
string appendText = File.ReadAllText(File1);
if (File.Exists(File2))
{
appendText += File.ReadAllText(File2);
}
}
}
}
seems like your question needs asp.net tag
context.Response.WriteFile(Settings.Default.negSourceLocation + "/neg.acc");
context.Response.WriteFile(Settings.Default.negSourceLocation + "/neg2.acc");
https://msdn.microsoft.com/en-us/library/dyfzssz9
This is what I did, not sure its the right way using C#,
static public string CombineFilesText(string mainPath, string clientPath)
{
string returnText = "";
FileStream mfs = File.OpenRead(mainPath);
using (StreamReader sr = new StreamReader(mfs))
{
returnText += sr.ReadToEnd();
}
FileStream cfs = File.OpenRead(clientPath);
using (StreamReader sr = new StreamReader(cfs))
{
returnText += sr.ReadToEnd();
}
return returnText;
}

How to create copy of file using StreamReader and StreamWriter

I need to use StreamReader to read a .txt file on a console application, then create a new file or backup with a different name but same content. The problem is i cant figure out how to use the content from the first file to place into the new one. (This is for a school thing and im new to C#)
using System;
using System.IO;
namespace UserListCopier
{
class Program
{
static void Main()
{
string fineName = "zombieList.txt";
StreamReader reader = new StreamReader(fineName);
int lineNumber = 0;
string line = reader.ReadLine();
while (line != null) {
lineNumber++;
Console.WriteLine("Line {0}: {1}", lineNumber, line);
line = reader.ReadLine();
}
StreamWriter writetext = new StreamWriter("zombieListBackup.txt");
writetext.Close();
System.Console.Read();
reader.Close();
}
}
}
Lets consider you have opened both streams, similar #jeff's solution, but instead of ReadToEnd (not really steaming effectively), you could buffer the transfer.
_bufferSize is an int set it to a buffer size that suits you (1024, 4096 whatever)
private void CopyStream(Stream src, Stream dest)
{
var buffer = new byte[_bufferSize];
int len;
while ((len = src.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, len);
}
}
here is a gist, containing a class which calculates the speed of transfer
https://gist.github.com/dbones/9298655#file-streamcopy-cs-L36
This will do that:
using System;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
using (var reader = new StreamReader(#"C:\MyOriginalFile.txt"))
using (var writer = new StreamWriter(#"C:\MyNewFile.txt", append: false))
{
writer.Write(reader.ReadToEnd());
}
Console.Read();
}
}
}
For files on the disk, you just need File.Copy(inputPath, outputPath). I'm not certain whether this streams the content efficiently, or whether it reads it all into memory and then writes it all out in one go.
So for large files, or if you have a stream that doesn't resolve to a path on the disk, you can efficiently copy from one to the other, using the following functions:
private void copyFile(string inputPath, string outputPath)
{
using (var inputStream = StreamReader(inputPath))
{
using (var outputStream = StreamWriter(outputPath))
{
copyToOutputStream(inputStream, outputStream);
}
}
}
private void copyToOutputStream(StreamReader inputStream, StreamWriter outputStream)
{
string line = null;
while ((line = inputStream.ReadLine()) != null)
{
outputStream.WriteLine(line);
}
outputStream.Write(inputStream.ReadToEnd());
}
This function copies from the input stream to the output stream one line at a time until the input stream ends. This means it only has one line in memory at a time (rather than the whole file) and that it can begin writing to the disk before the first stream has finished being read in / generated.
To answer the actual question:
using var reader = new StreamReader(someInput);
using var writer = new StreamWriter(someOutput);
reader.CopyTo(writer.BaseStream);
public static void ReadFromFile()
{
using (StreamReader sr = File.OpenText(#"D:\new.txt"))
{
string line = null;
while ((line = sr.ReadLine()) != null)
{
using (StreamWriter sw = File.AppendText(#"D:\output.txt"))
{
sw.WriteLine(line);
}
}
}
}

How to write into an existing textfile in windows phone?

If this is the code in opening a textfile "word.txt" in my solution explorer.
Stream txtStream = Application.GetResourceStream(new Uri("/sample;component/word.txt", UriKind.Relative)).Stream;
using (StreamReader sr = new StreamReader(txtStream))
{
string jon;
while (!sr.EndOfStream)
{
jon = sr.ReadLine();
mylistbox.ItemSource = jon;
}
}
How do i write and append in the existing textfile?
Here is an example
public static void WriteBackgroundSetting(string currentBackground)
{
const string fileName = "RecipeHub.txt";
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if(myIsolatedStorage.FileExists(fileName))
myIsolatedStorage.DeleteFile(fileName);
var stream = myIsolatedStorage.CreateFile(fileName);
using (StreamWriter isoStream = new StreamWriter(stream))
{
isoStream.WriteLine(currentBackground);
}
}
}

Categories