I'm trying to read a simple text file using reflection just as a learning case. I'm not getting an error, but I'm also not getting the desired result of "hello world". The variable stream is coming back null.
string output = "";
var asm = Assembly.GetExecutingAssembly();
using (var stream = asm.GetManifestResourceStream("ConsoleApp1.data1.txt"))
{
if (stream != null)
{
var reader = new StreamReader(stream);
output = reader.ReadToEnd();
Console.WriteLine(output);
}
}
You're reading from a manifest resource, which means the text file needs to be embedded in the dll. Right click on the file and choose Properties, then set the Build Action to "Embedded Resource".
Related
I use stream reader to read sql data. Although resourceName is correct and the resource Build Action property is Embedded Resource it still throws following error on StreamReader:
System.ArgumentNullException: Value cannot be null.
var namespace1 = typeof(Toolbox).Namespace;
var name1 = name.Replace('\\', '.');
string resourceName = $"{typeof(Toolbox).Namespace}.{name1}";
//Innosys.Ap.GetCurrentTimeKey.sql
using (Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)
)
{
using (StreamReader streamReader = new StreamReader(manifestResourceStream))
return streamReader.ReadToEnd();
}
Following are my debugging results so far.
namespace1 returns the correct name space used for the class from the project i.e. The class from which I call streamReader, resource file.
name1 returns resource file name with extension. ie. myquery.sql
resourcename which basically combines the path and the file name returns from my point of view the correct resouce address. i.e. myNamespace.myquery.sql
I am using xamrin.forms, and I am trying to access file and read it.
I have lastusername.txt as text file and I set the build action for it as "Content", actually I am trying to read file as the following:
var filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "lastusername.txt");
if (filename != null)
return System.IO.File.ReadAllText(filename);//error occurred here
else
return "";
I get the following Error:
System.IO.FileNotFoundException: Could not find file
Place your file within the Android Assets folder and assign it with a build type of "AndroidAsset".
Since your app's assets are read-only, you can then read it via the AssetManager, saving (copy) it somewhere else if it does not exist (i.e. the first time the app is run):
var fileName = "MyAssetBasedFile.txt";
if (!File.Exists(Path.Combine(CacheDir.Path, fileName)))
{
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader(assets.Open(fileName)))
using (StreamWriter sw = new StreamWriter(Path.Combine(CacheDir.Path, fileName), append: false))
sw.Write(sr.ReadToEnd());
}
string content;
using (StreamReader sr = new StreamReader(Path.Combine(CacheDir.Path, fileName)))
{
content = sr.ReadToEnd();
}
Log.Debug("SO", content);
The next time the app runs you will pick up the one in your cache dir.
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("xyz.project.Folder1.Folder2.SomeFile.Txt"))
{
TextReader tr = new StreamReader(stream);
string fileContents = tr.ReadToEnd();
}
var html = File.ReadAllText(Properties.Resources.FilesTypes);
var html = File.ReadAllText(#"E:\New folder (44)\New Text Document.txt");
In the original and what is working i used the lastl ine:
var html = File.ReadAllText(#"E:\New folder (44)\New Text Document.txt");
But then i added the text file to my project resources since i want the file to be in the program all the time and not to read it from the hard disk.
Then i added the code with the assembly
Assembly.GetExecutingAssembly().GetManifestResourceStream("xyz.project.Folder1.Folder2.SomeFile.Txt"))
{
TextReader tr = new StreamReader(stream);
string fileContents = tr.ReadToEnd();
}
But in this case i need to type the name of the file manualy.
So i tried this line:
var html = File.ReadAllText(Properties.Resources.FilesTypes);
But getting exception:
Illegal characters in path
I am using a web service that returns me some data. I am writing that data in a text file. my problem is that I am having a file already specified in the c# code, where I want to open a dialog box which ask user to save file in his desired location. Here I am posting code which I have used. Please help me in modifying my code. Actually after searching from internet, all are having different views and there is lot of changes in code required where as I do not want to change my code in extent. I am able to write the content in test file but how can I ask user to enter his desire location on computer?
StreamWriter file = new StreamWriter("D:\\test.txt");
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
// Get the response from the Internet resource.
HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
// Read the body of the response from the server.
StreamReader strm =
new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
string content = "";
for (int i = 0; i < symbols.Length; i++)
{
// Loop through each line from the stream,
// building the return XML Document string
if (symbols[i].Trim() == "")
continue;
content = strm.ReadLine().Replace("\"", "");
string[] contents = content.ToString().Split(',');
foreach (string dataToWrite in contents)
{
file.WriteLine(dataToWrite);
}
}
file.Close();
Try this
using (WebClient Client = new WebClient ())
{
Client.DownloadFile("http://www.abc.com/file/song/a.mpeg", "a.mpeg");
}
i want to open a css file using C# 4.5 and change only one file at a time.
Doing it like this gives me the exception - URI formats are not supported.
What is the most effective way to do it ?
Can I find the line and replace it without reading the whole file ?
Can the line that I am looking and than start to insert text until
cursor is pointing on some char ?
public void ChangeColor()
{
string text = File.ReadAllText("http://localhost:8080/game/Css/style.css");
text = text.Replace("class='replace'", "new value");
File.WriteAllText("D://p.htm", text);
}
I believe File.ReadAllText is expecting a file path, not a URL.
No, you cannot search/replace sections of a text file without reading and re-writing the whole file. It's just a text file, not a database.
most effective way to do it is to declare any control you want to alter the css of as "runat=server" and then modify the CssClass property of it. There is no known alternative way to modify the css file directly. Any other hacks is just that.. a hack and very innefficient way to do it.
As mentioned before File.ReadAllText does not support url. Following is a working example with WebRequest:
{
Uri uri = new Uri("http://localhost:8080/game/Css/style.css");
WebRequest req = WebRequest.Create(uri);
WebResponse web = req.GetResponse();
Stream stream = web.GetResponseStream();
string content = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
content = sr.ReadToEnd();
}
content.Replace("class='replace'", "new value");
using (StreamWriter sw = new StreamWriter("D://p.htm"))
{
sw.Write(content);
sw.Flush();
}
}