I need to read a file from my resources and add it to a list.
my code:
private void Form1_Load(object sender, EventArgs e)
{
using (StreamReader r = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.myText.txt")))
{
//The Only Options Here Are BaseStream & CurrentEncoding
}
}
Ive searched for this and only have gotten answers like "Assembly.GetExecutingAssembly...." but my program doesnt have the option of Assembly.?
Try something like this :
string resource_data = Properties.Resources.test;
List<string> words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).ToList();
Where
You need to include using System.Reflection; in your header in order to get access to Assembly. This is only for when you mark a file as "Embedded Resource" in VS.
var filename = "MyFile.txt"
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNameSpace." + filename));
As long as you include 'using System.Reflection;' you can access Assembly like this:
Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace." + filename);
Or if you don't need to vary filename just use:
Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.MyFile.txt");
The full code should look like this:
using(var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.myText.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do some stuff here with your textfile
}
}
Just to follow on this, AppDeveloper solution is the way to go.
string resource_data = Properties.Resources.test;
string [] words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
foreach(string lines in words){
.....
}
[TestCategory("THISISATEST")]
public void TestResourcesReacheability()
{
byte[] x = NAMESPACE.Properties.Resources.ExcelTestFile;
string fileTempLocation = Path.GetTempPath() + "temp.xls";
System.IO.File.WriteAllBytes(fileTempLocation, x);
File.Copy(fileTempLocation, "D:\\new.xls");
}
You get the resouce file as a byte array, so you can use the WriteAllBytes to create a new file. If you don't know where can you write the file (cause of permissions and access) you can use the Path.GetTempPath() to use the PC temporary folder to write the new file and then you can copy or work from there.
Related
There are a lot of different ways to read and write files (text files, not binary) in C#.
I just need something that is easy and uses the least amount of code, because I am going to be working with files a lot in my project. I only need something for string since all I need is to read and write strings.
Use File.ReadAllText and File.WriteAllText.
MSDN example excerpt:
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
...
// Open the file to read from.
string readText = File.ReadAllText(path);
In addition to File.ReadAllText, File.ReadAllLines, and File.WriteAllText (and similar helpers from File class) shown in another answer you can use StreamWriter/StreamReader classes.
Writing a text file:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
Reading a text file:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readText = readtext.ReadLine();
}
Notes:
You can use readtext.Dispose() instead of using, but it will not close file/reader/writer in case of exceptions
Be aware that relative path is relative to current working directory. You may want to use/construct absolute path.
Missing using/Close is very common reason of "why data is not written to file".
FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
using(StreamReader sr = new StreamReader(fs))
{
using (StreamWriter sw = new StreamWriter(Destination))
{
sw.Writeline("Your text");
}
}
The easiest way to read from a file and write to a file:
//Read from a file
string something = File.ReadAllText("C:\\Rfile.txt");
//Write to a file
using (StreamWriter writer = new StreamWriter("Wfile.txt"))
{
writer.WriteLine(something);
}
using (var file = File.Create("pricequote.txt"))
{
...........
}
using (var file = File.OpenRead("pricequote.txt"))
{
..........
}
Simple, easy and also disposes/cleans up the object once you are done with it.
#AlexeiLevenkov pointed me at another "easiest way" namely the extension method. It takes just a little coding, then provides the absolute easiest way to read/write, plus it offers the flexibility to create variations according to your personal needs. Here is a complete example:
This defines the extension method on the string type. Note that the only thing that really matters is the function argument with extra keyword this, that makes it refer to the object that the method is attached to. The class name does not matter; the class and method must be declared static.
using System.IO;//File, Directory, Path
namespace Lib
{
/// <summary>
/// Handy string methods
/// </summary>
public static class Strings
{
/// <summary>
/// Extension method to write the string Str to a file
/// </summary>
/// <param name="Str"></param>
/// <param name="Filename"></param>
public static void WriteToFile(this string Str, string Filename)
{
File.WriteAllText(Filename, Str);
return;
}
// of course you could add other useful string methods...
}//end class
}//end ns
This is how to use the string extension method, note that it refers automagically to the class Strings:
using Lib;//(extension) method(s) for string
namespace ConsoleApp_Sandbox
{
class Program
{
static void Main(string[] args)
{
"Hello World!".WriteToFile(#"c:\temp\helloworld.txt");
return;
}
}//end class
}//end ns
I would never have found this myself, but it works great, so I wanted to share this. Have fun!
These are the best and most commonly used methods for writing to and reading from files:
using System.IO;
File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it.
File.ReadAllText(sFilePathAndName);
The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.
Append text to an existing file:
private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
string sTextToAppend = txtMainUserInput.Text;
//first, check to make sure that the user entered something in the text box.
if (sTextToAppend == "" || sTextToAppend == null)
{MessageBox.Show("You did not enter any text. Please try again");}
else
{
string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
if (sFilePathAndName == "" || sFilePathAndName == null)
{
//MessageBox.Show("You cancalled"); //DO NOTHING
}
else
{
sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
File.AppendAllText(sFilePathAndName, sTextToAppend);
string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
}//end nested if/else
}//end if/else
}//end method AppendTextToExistingFile_Click
Get file name from the user via file explorer/open file dialog (you will need this to select existing files).
private string getFileNameFromUser()//returns file path\name
{
string sFileNameAndPath = "";
OpenFileDialog fd = new OpenFileDialog();
fd.Title = "Select file";
fd.Filter = "TXT files|*.txt";
fd.InitialDirectory = Environment.CurrentDirectory;
if (fd.ShowDialog() == DialogResult.OK)
{
sFileNameAndPath = (fd.FileName.ToString());
}
return sFileNameAndPath;
}//end method getFileNameFromUser
Get text from an existing file:
private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
string sFileNameAndPath = getFileNameFromUser();
txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}
Or, if you are really about lines:
System.IO.File also contains a static method WriteAllLines, so you could do:
IList<string> myLines = new List<string>()
{
"line1",
"line2",
"line3",
};
File.WriteAllLines("./foo", myLines);
It's good when reading to use the OpenFileDialog control to browse to any file you want to read. Find the code below:
Don't forget to add the following using statement to read files: using System.IO;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
To write files you can use the method File.WriteAllText.
class Program
{
public static void Main()
{
//To write in a txt file
File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");
//To Read from a txt file & print on console
string copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
Console.Out.WriteLine("{0}",copyTxt);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//Write a file
string text = "The text inside the file.";
System.IO.File.WriteAllText("file_name.txt", text);
//Read a file
string read = System.IO.File.ReadAllText("file_name.txt");
MessageBox.Show(read); //Display text in the file
}
Reading from file
string filePath = #"YOUR PATH";
List<string> lines = File.ReadAllLines(filePath).ToList();
Writing to file
List<string> lines = new List<string>();
string a = "Something to be written"
lines.Add(a);
File.WriteAllLines(filePath, lines);
Simply:
String inputText = "Hello World!";
File.WriteAllText("yourfile.ext",inputText); //writing
var outputText = File.ReadAllText("yourfile.ext"); //reading
You're looking for the File, StreamWriter, and StreamReader classes.
This question already has an answer here:
Modify the content of specific line in text file
(1 answer)
Closed 8 years ago.
I'm having a textfile say something like this:
#TITLE:What's Up
#ARTIST:4 Non Blondes - Whats Up
#MP3:Four Non Blondes - Whats Up.mp3
#COVER:4 Non Blondes - Whats Up [CO].jpg
#BACKGROUND:4 Non Blondes - Whats Up [CO].jpg
#BPM:135
#GAP:32100
it's saved as 4 Non Blondes - Whats Up.txt
In the same folder there's a MP3 file which is in this example: 4 Non Blondes - Whats Up.mp3
What i want is to replace the line:
#MP3:Four Non Blondes - Whats Up.mp3
into this line:
#MP3:4 Non Blondes - Whats Up.mp3
Every MP3 line has infront of the line this:
#MP3:[Songname].mp3
I know i can do this manually but i have like 2k files like this, and they all need to link to the correct mp3 file. I'm trying this in C#, but without luck.
This is what i've tried so far:
private static void testMethod(string path)
{
var x = System.IO.Directory.GetDirectories(path);
foreach (var directory in x)
{
string[] mp3Files = System.IO.Directory.GetFiles(directory, "*.mp3");
string[] txtFiles = System.IO.Directory.GetFiles(directory, "*.txt");
string MP3FileNameWithExtensions = System.IO.Path.GetFileName(mp3Files[0]);
Console.WriteLine(txtFiles[0]);
var lines = System.IO.File.ReadAllLines(txtFiles[0]);
for (int i = 0; i < lines.Length; i++)
{
if(lines[i].Contains("#MP3")){
Console.WriteLine("Jeeeej working");
lines[i] = "#MP3:"+MP3FileNameWithExtensions;
System.IO.File.WriteAllLines(txtFiles[0], lines);
}
}
}
}
As the filename of the .txt file is [Songname].txt, you can use Path.GetFilenameWithoutExtension(files[i]) to get [Songname]. Then replace the #MP3 line with the filename + ".mp3". Now write out the file.
N.B. You will probably want to make a copy of the directory you are working on just in case something goes wrong.
I know I am late to the party but here is an example.
public void FixTheFiles(String startFolderPath)
{
foreach (String dirName in Directory.GetDirectories(startFolderPath))
{
FixTheFiles(dirName);
}
foreach (String fileName in Directory.GetFiles(startFolderPath))
{
FileInfo fi = new FileInfo(fileName);
if (fi.Extension.Equals("MP3"))
{
String fileContents = "";
using (StreamReader sr = new StreamReader(File.Open(fileName.Replace(".mp3",".txt"),FileMode.Open)))
{
String currentLine = sr.ReadLine();
if (currentLine.StartsWith("#MP3:"))
{
currentLine = "#MP3:" + fileName.Substring(fileName.LastIndexOf('\\')+1);
}
fileContents += currentLine;
}
using (StreamWriter sw = new StreamWriter(File.Open(fileName.Replace(".mp3",".txt"),FileMode.Open)))
{
sw.Write(fileContents);
}
}
}
}
I would simutaneously open a stream reader and a stream writer (with a different file name) and go through each file one line at a time searching for whatever changes you need to make. You can select your file names with an openfiledialog with Multiselect = true or run this command in a command prompt window to generate a textfile to paste in your code with quotation marks around them as initial values for a string array instantiation.
dir *.mp3 /b > filenames.txt
string[] array = new string[] {"file0.mp3",
"file1.mp3",
"file2.mp3",
"file3.mp3",
"file4.mp3",
"file5.mp3"};
I am having a problem writing the files in folders and subfolders .
For Example:- test is the main folder
1) C:\test\
and i want to read and write the subfolder files
2)C:\test\12-05-2011\12-05-2011.txt
3)C:\test\13-05-2011\13-05-2011.txt
4)C:\test\14-05-2011\14-05-2011.txt
My code is:
private void button1_Click(object sender, EventArgs e)
{
const string Path1 = #"C:\test";
DoOnSubfolders(Path1);
try
{
StreamReader reader1 = File.OpenText(Path1);
string str = reader1.ReadToEnd();
reader1.Close();
reader1.Dispose();
File.Delete(Path1);
string[] Strarray = str.Split(new char[] { Strings.ChrW(10) });
int abc = Strarray.Length - 2;
int xyz = 0;
while (xyz <= abc)
}
I am getting an error. The error is
Access to the path 'C:\test' is denied.
Can anyone say me what i need to change in this code?
At first you could flatten your recursive calls by calling DirectoryInfo.GetFiles(string, SearchOption) and setting the SearchOption to AllDirectories.
What's also a common mistake (but not clear from your question) is that a directory needs to be created, before you can create a file. Simply call Directory.CreateDirectory(). And put in the complete path (without filename) into it. It will automatically do nothing if the directory already exists and is also able to create the whole needed structure. So no checks or recursive calls are needed (maybe a try-catch if you don't have write access).
Update
So here is an example that reads in a file, does some conversion on each line and writes the result into a new file. If this works properly the original file will be replaced by the converted one.
private static void ConvertFiles(string pathToSearchRecursive, string searchPattern)
{
var dir = new DirectoryInfo(pathToSearchRecursive);
if (!dir.Exists)
{
throw new ArgumentException("Directory doesn't exists: " + dir.ToString());
}
if (String.IsNullOrEmpty(searchPattern))
{
throw new ArgumentNullException("searchPattern");
}
foreach (var file in dir.GetFiles(searchPattern, SearchOption.AllDirectories))
{
var tempFile = Path.GetTempFileName();
// Use the using statement to make sure file is closed at the end or on error.
using (var reader = file.OpenText())
using (var writer = new StreamWriter(tempFile))
{
string line;
while (null != (line = reader.ReadLine()))
{
var split = line.Split((char)10);
foreach (var item in split)
{
writer.WriteLine(item);
}
}
}
// Replace the original file be the converted one (if needed)
////File.Copy(tempFile, file.FullName, true);
}
}
In your case you could call this function
ConvertFiles(#"D:\test", "*.*")
To recursively walk the sub-folders, you need a recursive function ie. One that calls itself. here is an example that should be enough for you to work with:
static void Main(string[] args)
{
const string path = #"C:\temp\";
DoOnSubfolders(path);
}
private static void DoOnSubfolders(string rootPath)
{
DirectoryInfo d = new DirectoryInfo(rootPath);
FileInfo[] fis = d.GetFiles();
foreach (var fi in fis)
{
string str = File.ReadAllText(fi.FullName);
//do your stuff
}
DirectoryInfo[] ds = d.GetDirectories();
foreach (var info in ds)
{
DoOnSubfolders(info.FullName);
}
}
You need use class Directory info and FileInfo.
DirectoryInfo d = new DirectoryInfo("c:\\test");
FileInfo [] fis = d.GetFiles();
DirectoryInfo [] ds = d.GetDirectories();
Here's a quick one liner to write the contents of all text files in a given directory (and all subdirectories) to the console:
Directory.GetFiles(myDirectory,"*.txt*",SearchOption.AllDirectories)
.ToList()
.ForEach(a => Console.WriteLine(File.ReadAllText(a)));
This code:
const string Path1 = #"C:\test";
StreamReader reader1 = File.OpenText(Path1);
Says open "c:\test" as a text file... The error you're getting is:
Access to the path 'C:\test' is denied
You're getting the error because as you stated above, 'c:\test' is a folder. You can't open folders like they are text files, hence the error...
A basic (full depth search) for files with a .txt extension looks like this:
static void Main(string[] args) {
ProcessDir(#"c:\test");
}
static void ProcessDir(string currentPath) {
foreach (var file in Directory.GetFiles(currentPath, "*.txt")) {
// Process each file (replace this with your code / function call /
// change signature to allow a delegate to be passed in... etc
// StreamReader reader1 = File.OpenText(file); // etc
Console.WriteLine("File: {0}", file);
}
// recurse (may not be necessary), call each subfolder to see
// if there's more hiding below
foreach (var subFolder in Directory.GetDirectories(currentPath)) {
ProcessDir(subFolder);
}
}
Have a look at http://support.microsoft.com/kb/303974 for a start. The secret is Directory.GetDirectories in System.IO.
You have to configure (NTFS) security on the c:\Test folder.
Normally you would have the application run under non-admininstrator account so the account that is running the program should have access.
If you are running on Vista or Windows 7 with UAC, you might be an administrator but you will not be using the administrative (elevated) permissions by default.
EDIT
Look at these lines:
const string Path1 = #"C:\test";
DoOnSubfolders(Path1);
try
{
StreamReader reader1 = File.OpenText(Path1);
That last line is trying to read the FOLDER 'c:\test' as if it was a text file.
You can't do that. What are you trying to accomplish there?
What i'm trying to do is open a config file. For each object this config file references it uses the tags BEGINOB ENDOB. I'm trying to read the while thing and Split on ENDOB, and IF the first set contains BEGINOB+"\r\n"+"13" write all the contents to a console line. I have this code here but i'm having a hard time figure out my split.
using (FileStream redfs = new FileStream(redfoldertarget, FileMode.Open))
using (StreamReader rdrred = new StreamReader(redfs))
{
while (!rdrred.EndOfStream)
{
string linesplitnew = "ENDOB";
string[] redsplitline = rdrred.ReadToEnd().Split(Convert.ToString(linesplitnew));
string redpullline = "BEGINOB"+"\r\n"+"13";
if(redsplitline.Contains(redpullline))
{
Console.WriteLine(redsplitline);
}
}
}
You need to call the Split overload that takes an array of strings, like this:
string[] redsplitline = rdrred.ReadToEnd().Split(new string[] { linesplitnew }, StringSplitOptions.None);
i have this code snippet
private List<string> FolderOne(string Folder)
{
string filena;
DirectoryInfo dir = new DirectoryInfo(Folder);
FileInfo[] files = dir.GetFiles("*.mp3", SearchOption.AllDirectories);
List<string> str = new List<string>();
foreach (FileInfo file in files)
{
str.Add(file.FullName);
filena = file.FullName;
filena.Replace("*.mp3", "*.jpg");
if (filena.Length > 0)
{
pictureBox1.Image = new System.Drawing.Bitmap(filena.ToString()); //I receive a error "Parameter is not valid."
}
}
return str;
}
My purpose was to make read the picture box the file.fullname ".mp3" in the same folder but end with ".jpg",infact i have 2 file in a folder the first one is a song "firstsong.mp3" and the second one a picture "firstsong.jpg" the difference between them is the final extension so i try to make read to picturebox the same filename but with extension ".*jpg" and i receive an error "Parameter is not valid." in the line code "pictureBox1.Image = new System.Drawing.Bitmap(filena.ToString());".
How i can work out that?
Thanks for your attention
Nice Regards
There are some other issues with your code. First off, you are storing all the mp3 file names, but only displaying the last image loaded.
As far as replacing the extension, use Path's method to do that:
string musicFile = "mysong.mp3";
string imageFile = Path.ChangeExtension(musicFile, "jpg");
Switch to:
filena = filena.Replace(".mp3", ".jpg");
if (filena.Length > 0)
{
pictureBox1.Image = new System.Drawing.Bitmap(filena);
}
The main problem is with filena.Replace("*.mp3", "*.jpg");
There are two issues in that line.
First, you're searching on "*.mp3" instead of just ".mp3". The individual filenames do not have the * character, and string.Replace doesn't use regular expressions, just string matching.
Second, strings in .NET are immutable. They cannot be changed once they're created. This means that you can't replace the value of a string in place - you always return a new string. So string.Replace(...) will return a new string.
I'd add to the previous suggestions by adding that you should check that the jpg exists by doing the following:
if (File.Exists(jpgFilePath)) {
pictureBox1.Image = new System.Drawing.Bitmap(jpgFilePath);
}