How to store the file in a string - c#

I am trying to store this file in a string.but i don know how to do it??can you
please help me.This is my program
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace Sample_Program_For_CC_ utility
{
class Program
{
static void Main(string[] args)
{
TextReader tr = new StreamReader(#"C://Users//Darts//Desktop//sample//00004.txt");
Console.WriteLine(tr.ReadToEnd());
tr.Close();//
}
}
}

It's not really clear what's going wrong with the code you've given, but it's simpler to use File.ReadAllText. For eaxmple:
string file = #"C:\Users\Darts\Desktop\sample\00004.txt"
string text = File.ReadAllText(file);

You could just do:
string text = System.IO.File.ReadAllText(#"C://Users//Darts//Desktop//sample//00004.txt");
See http://msdn.microsoft.com/en-us/library/ezwyzy7b.aspx

string s = System.IO.File.ReadAllText( yourPathAndFile );

you can use ReadAllText
string fileContents = File.ReadAllText("c:\\filename.txt")
btw. you don't need # if you are using double backslash, and you have to use backslash and not slash

String theString = tr.ReadToEnd();
As .ReadToEnd() returns a string.

You can load the file contents in a string as follows.
string fileContents = tr.ReadToEnd();

FileStream FS = new FileStream(#"C://Users//Darts//Desktop//sample//00004.txt", FileMode.Open, FileAccess.Read);
TextReader tr = new StreamReader(#"C://Users//Darts//Desktop//sample//00004.txt");
Console.WriteLine(tr.ReadToEnd());
tr.Close();

Related

Read a file into a string in C#

I am trying to read a file into a string which then I will send to another application.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:\text.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
I am getting the error:
The file could not be read:
Could not find file 'c:\users\andymarkmn\documents\visual studio 2015\Projects\FileApplication\FileApplication\bin\Debug\text.txt'.
I have tried putting the file in bin debug folders as well.
How to make sure the code works ?
EDIT: As suggested, I tried using the different ways.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string filepath = "c:\\text.txt";
try
{
string lines = File.ReadAllText(filepath);
Console.Write(lines);
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
I still get the error:
The file could not be read:
Could not find file 'c:\text.txt'.
You have accidentally used an unwanted escape sequence in your filename string.
new StreamReader("c:\text.txt")
should be
new StreamReader(#"c:\text.txt")
Otherwise \ gets treated as an escape character, at \t is a tab character. This leaves an unexpected result, and the wrong path for the file.
# instructs the compiler to ignore any escape characters in the string.
"c:\text.txt" will not work as \ is an escape character.
use #"c:\text.txt" or "c:\\text.txt"
When StreamReader is given a non-qualified path as a parameter, it will look for the file in the application's working directory as you have done:
using (StreamReader sr = new StreamReader("c:\text.txt"))
If the file isn't located there, probably you should give StreamReader a fully qualified path:
using (StreamReader sr = new StreamReader(#"c:\text.txt"))
//or...
using (StreamReader sr = new StreamReader("c:\\text.txt"))
Try:
using (StreamReader sr = new StreamReader(#"C:\text.txt"))
If you use c:\text, C# considers that the string has a tabulador between C: and text.txt.

C# File directory issue

I have created a high score file for my game and I am having problems reading it.
When I change computers my USB drive changes letter .eg from drive E to drive G.
This is causing problems with reading the file. (as I use string path = #"g:\Scores.txt";)
So my question is.... can I set a default path to the program location??
My current code:-
string path = #"g:\Scores.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
}
any help is appreciated.
Is the game on your USB drive as well? Do you want to save the file in the same directory as the game, or in a directory somewhere around it? Do something like this:
using System;
using System.IO;
using System.Reflection;
...
string thisAsmFile = Assembly.GetExecutingAssembly().Location;
string thisAsmDir = Path.GetDirectoryName(thisAsmPath);
string highScoreFile = Path.Combine(thisAsmDir, "scores.txt");
If your program is in the same folder as the file ( Eg. in G:\ ), then you can simply access the file with his name : `path = "Scores.txt".
In that case there is no need to know where is the file
You should use your application path, not an absolute path.
You may do something like this:
using System.IO;
using System.Windows.Forms;
string appPath = Path.GetDirectoryName(Application.ExecutablePath);

Wrong encoding, output file gives � instead of normal char

I want to make a program that searches a file for desired chars in words (letters č ć ž š), replaces them with c z s etc. and saves the file. In my attempt, however, I get some stupid signs, so that means it opens the file wrongly. When I try to add encoding.unicode it gives me errors (shown below). And one more question, how do I make a program which opens files by dragging them in an .exe file.
Error 3 The best overloaded method match for
'System.IO.File.Open(string, System.IO.FileMode,
System.IO.FileAccess)' has some invalid
arguments C:\Users\Vulisha\AppData\Local\Temporary
Projects\ConsoleApplication1\Program.cs 14 59 ConsoleApplication1
Error 4 Argument '3': cannot convert from 'System.Text.Encoding' to
'System.IO.FileAccess' C:\Users\Vulisha\AppData\Local\Temporary
Projects\ConsoleApplication1\Program.cs 14 122 ConsoleApplication1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (StreamReader stream = new StreamReader(File.Open(#"C:\Users\Vulisha\Desktop\titl.txt", FileMode.Open)))
{
string fileText = stream.ReadToEnd();
// Do your replacements
fileText = fileText.Replace(#"č", #"c");
fileText = fileText.Replace(#"ć", #"c");
fileText = fileText.Replace(#"š", #"s");
fileText = fileText.Replace(#"ž", #"z");
fileText = fileText.Replace(#"đ", #"d");
fileText = fileText.Replace(#"Č", #"C");
fileText = fileText.Replace(#"Č", #"C");
fileText = fileText.Replace(#"Š", #"S");
fileText = fileText.Replace(#"Ž", #"Z");
fileText = fileText.Replace(#"Đ", #"D");
using (StreamWriter writer = new StreamWriter(File.Open(#"titl.txt", FileMode.Create)))
{
// You do a create because the new file will have less characters than the old one
writer.Write(fileText);
}
}
}
}
}
You need to be more careful with placement of parentheses. You need
new StreamWriter(File.Open(#"titl.txt", FileMode.Create), Encoding.Unicode)
but you wrote
new StreamWriter(File.Open(#"titl.txt", FileMode.Create, Encoding.Unicode))
See the difference?

Replace method doesn't replace dashes to empty string

I'm trying to hash a file using SHA1. The result looks like this: B7-DB-B9-93-E7-2F-6F-EB-6D-CD-CC-A8-DE-D2-F1-01-6E-8A-53-BC
How to I replace dashes to empty string or just remove them?
The code trying to replace the dashes, but it seems like it don't change anything and dashes are still in place.
using (HashAlgorithm hashSHA1 = new SHA1Managed())
using (Stream file = new FileStream(ofdBrowse.FileName, FileMode.Open, FileAccess.Read))
{
byte[] hash = hashSHA1.ComputeHash(file);
txtSHA1.Text = BitConverter.ToString(hash).Replace("-", "");
}
Difference between dash and hyphen?
http://msdn.microsoft.com/en-us/library/3a733s97.aspx
Not really sure. Just my guess in the dark.
The code you've give definitely removes the dashes. Short but complete program to demonstrate that:
using System;
using System.IO;
using System.Security.Cryptography;
class Test
{
static void Main(string[] args)
{
using (HashAlgorithm hashSHA1 = new SHA1Managed())
{
// Actual data doesn't matter
using (Stream data = new MemoryStream())
{
byte[] hash = hashSHA1.ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", ""));
}
}
}
}
So, potential cause of your problem:
You're not running the build you think you are
You've got other code which does the hashing but doesn't have the Replace call
You're looking at the wrong bit of the UI :)
It's hard to really guess which of those (or anything else) is the problem, but that code isn't it...

Issue in writing special characters to Excel

I have a few reports that are exported to Excel. The problem is whereever there are special characters, it is being replaced by some funny symbols
For example, '-'(hyphen) was replaced by –...
Any help to solve the problem??
The most straight forward way is to encode the text file as UTF-8. I ran the following code, opened the resulting hyphen.txt file in Excel 2007 and it worked as expected:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var hyphen = "\u2010\r\n";
var encoding = Encoding.UTF8;
var bytes = encoding.GetBytes(hyphen);
using (var stream = new System.IO.FileStream(#"c:\tmp\hyphen.txt", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
{
stream.Write(bytes, 0, bytes.Length);
}
}
}
}
This is the code -- view at PasteBin.

Categories