Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have seen many examples/ tutorials about VB.NET or C#.NET where the author is using a FileStream to write/read from a file. My question is there any benefit to this method rather than using System.IO.File.Read/Write ? Why are the majority of examples using FileStream to when the same can be achieved using just a single line of code?
FileStream gives you a little more control over writing files, which can be beneficial in certain cases. It also allows you to keep the file handle open and continuously write data without relinquishing control. Some use cases for a stream:
Multiple inputs
Real time data from a memory/network stream.
System.IO.File contains wrappers around file operations for basic actions such as saving a file, reading a file to lines, etc. It's simply an abstraction over FileStream.
From the .NET source code here is what WriteAllText does internally:
private static void InternalWriteAllText(string path,
string contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamWriter sw = new StreamWriter(path, false, encoding))
sw.Write(contents);
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I'm creating an attachment section for a webpage that takes said attachment, converts it to base64 and passes it to xml gateway.
Is there any reason for me to save said file locally? The file size limit is 5mb.
Current set up seems to work;
byte[] attachBytes = new byte[attach.ContentLength];
using (BinaryReader theReader = new BinaryReader(attach.InputStream))
{
attachBytes = theReader.ReadBytes(attach.ContentLength);
}
model.filename = attach.FileName;
model.base64convert = Convert.ToBase64String(attachBytes);
VS Saving(File isn't required to be stored on the server)
attach.SaveAs("C:/temp/Attachfiles/" + attach.FileName);
byte[] attachBytes = new byte[attach.ContentLength];
using (BinaryReader theReader = new BinaryReader(attach.InputStream))
{
attachBytes = theReader.ReadBytes(attach.ContentLength);
}
model.filename = attach.FileName;
model.base64convert = Convert.ToBase64String(attachBytes);
Mainly just wondering the downsides of doing it how I am. I'm thinking there is no difference as I am not reading the saved file back in but I'm still learning and don't want to miss anything.
Your question is a bit open ended, but answerable.
If you have to have some record of receiving the file before sending it on, then save it. However, there are downsides to saving a file
you could run out of space
the file, if it contains anything sensitive, is stored in the clear
you're introducing a point of failure (e.g. can't save file) for no gain
So, as specified, don't do it. If your requirements evolve you can always re-evaluate that decision.
As mentioned in the comments, a save may be reasonable if you are doing something like a resend in case of failure; but even then I suggest not keeping the file around forever, and usually storage at/on a web server is a bad idea for the reasons above.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What exactly does this statement mean?
TextWriter textWriter = new StreamWriter(#System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
I have learned dotnet but haven't worked in any of the development project. Now that I am looking for a job switch, I am making use of some of the sites like Hackerrank. So I just want to know what exactly this statement do and if we omit this sentence what will happen to the code.
glad you are curious and ambitions about probramming.
The following statement
TextWriter textWriter = new StreamWriter(#System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
Simply creates an IO stream that allows you to write to a file on a file system. It is getting the file path that it will be writing to from the environment variable "OUTPUT_PATH" which would need to be setup external from this code.
Presumably the following lines of code will be logging some information to the file.
If you simply omit this line and there were following lines using the local variable textWriter your application would not compile. If you removed all references to this variable nothing would be written to a file.
You should be aware that using a Streamwriter can leave a file open and in use on the file system if you don't dispose of it properly. I would suggest whenever writing to a file to enclose this line in a using statement which will automatically close the file and flush whatever is in the buffer out to the file. Another thing to note is that when writing to files the streamwriter will not automatically "flush" the buffer out to file. This is particularly interesting when you are monitoring an application from files.
For more information on using a testwriter have a look at the MS docs here: https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter?view=netcore-3.1
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
In c# How many way to open file? Which one is best? and how to open .exe file? Sorry for silly question but i am new in c#.
using (StreamReader srStreamReader = new StreamReader(sString))
{
while ((sline = srStreamReader.ReadLine()) != null)
{
Console.WriteLine(sline);
}
}
I am use this code for this but am not able. so please help
If I understood the problem correctly
You can use like this
string path;
byte[] bufferArray = File.ReadAllBytes(path);
string base64EncodedString = Convert.ToBase64String(bufferArray );
bufferArray = Convert.FromBase64String(base64EncodedString );
File.WriteAllBytes(path, bufferArray );
By open file do you mean execute it or read line by line?
If execute then probably something like this is the answer:
Process.Start("C:\\");
From the code you've provided, it looks like you want to be able to view the source of an .exe. This can't be done without using a decompiler and knowing what the application was compiled with.
If you're trying to execute the .exe file, then take a look at the static method System.Diagnostics.Process.Start(filePath).
If you're trying to actually read the contents, you can use ILSpy or other similar software to decompile the application to view source. ILSpy has source available on GitHub, so you'll be able to use that to get the contents you want.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to do my own Minecraft Launcher for Moded Minecraft. And I have a issue: I need to extract content of one *.jar file to another. I tried a lot of things and I am totally desperate.
Basicly, I need to do this in code.
As Andrew briefly mentioned, there are some good .NET libraries for manipulating zip files. I've found DotNetZip to be very useful, and there are lots of helpful worked examples here.
In answer to your question, if you just want to copy the contents of one *.jar file to another, keeping original content in the target file, please try the following. I'm using the .NET zip mentioned above (which also has a NuGet package!):
using (ZipFile sourceZipFile = ZipFile.Read("zip1.jar"))
using (ZipFile targetZipFile = ZipFile.Read("zip2.jar"))
{
foreach (var zipItem in sourceZipFile)
{
if (!targetZipFile.ContainsEntry(zipItem.FileName))
{
using (Stream stream = new MemoryStream())
{
// Write the contents of this zip item to a stream
zipItem.Extract(stream);
stream.Position = 0;
// Now use the contents of this stream to write to the target file
targetZipFile.AddEntry(zipItem.FileName, stream);
// Save the target file. We need to do this each time before we close
// the stream
targetZipFile.Save();
}
}
}
}
Hope this helps!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm implementing a Windows application to make planning projects easier at my workplace and I was wondering if there's any clever way of making a txt-file nicely structured.
The application is really very simple, pretty much what it does is give the user a question which is answered in a textbox bellow. The question AND the answer are then both sent to a file but it looks very tacky.
Example:
Question?Answer!Question?Answer!
I would like it to be more like this:
Question?
Answer!
Question?
Answer!
I was also curious about other types files, is it possible to use Pdf or MS word the same way as txt?
You can use File.AppendAllLines() and pass in the different strings as an array. They will appear as separate lines in the text file. You'll also need to add a using System.IO at the top of your file.
For example:
// Ensure file exists before we write
if (!File.Exists("<YOUR_FILE_PATH>.txt"))
{
using (File.CreateText("<YOUR_FILE_PATH>.txt")) {}
}
File.AppendAllLines("<YOUR_FILE_PATH>.txt", new string[] {
"Question1",
"Answer1",
"Question2",
"Answer2",
"Question3",
"Answer3"
});
I hope this is what you're after - the question is a little vague.
As for Word and PDF files, this is more complex. Here's a link to a StackOverflow question about Word:
How can a Word document be created in C#?
and one about PDF:
Creating pdf files at runtime in c#
For a simple text file you could use
StringBuilder fileData = new StringBuilder();
fileData.AppendLine("Question: blah! blah! blah! blah!");
fileData.AppendLine("Answer: blah! blah! blah! blah!");
FileStream fs = new FileStream("yourFile.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.Write(fileData.ToString());
sw.Flush();
fs.Flush();
fs.Close();
But of course it won't give you that bold question flavor, for that you would have to use something else,
like MS Word interop, to learn that visit here.
I wanted to mention the String.Format function.
suppose, you have your strings question and answer, you could do some
using (var stream = new StreamWriter('myfile.txt', true)) // append=true
stream.Write(String.Format("\n{0}\n{1}\n\n{2}\n",
question,
new String('=',question.Length),
answer);
to get a text file like
Question 1
==========
Answer
Second Question
===============
Answer
You might also want to use String.Trim() on question to get rid of leading and trailing whitespace (question = question.Trim()), so the "underline" effect looks nicely.