create txt file in selected location in c# application [closed] - c#

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 developing a c# application. In this Form I have added 2 buttons.
Those are Browse and Create File Buttons.
Now I want to do is use browse button to browse a location and when click Create file button, create a text file in that location.

Have a look at
SaveFileDialog Class
Prompts the user to select a location for saving a file.
or
FolderBrowserDialog Class
Prompts the user to select a folder.
File.Create Method
Creates a file in the specified path.
or even
File.CreateText Method
Creates or opens a file for writing UTF-8 encoded text

on click event do it like this
//if you want to overwrite the file if it already exists you can bypass this check
if (File.Exists(path))
{
File.Delete(path);
}
// Create the file.
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
if you don't intend to write anything
FileStream fs = File.Create(path);
fs.Close(); //this needs to be done
You need to read this.

Related

C# How do I prevent a file from saving without the asked extension? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm currently writing a program and using my own file extension ".pn" for these files. When I use the BinaryWriter in FileMode.Create to write to the file "primes.pn" and then look in the file explorer it does not have the extension I asked. My file explorer has display file extensions turned on. How could I prevent this from happening/what is causing this?
Additionally the check for whether "primes.pn" exists passes but then when checking the length of the file it throws a System.IO.FileNotFoundException.
if (!File.Exists("res_divisibility/primes.pn") && bytes.Count > new FileInfo("res_divisibility/primes.pn").Length)
{
BinaryWriter bw = new BinaryWriter(new FileStream("res_divisibility/primes.pn", FileMode.Create));
foreach(byte b in bytes)
bw.Write(b);
}
Still not sure what was causing the problem but File.WriteAllBytes()solves this issue. The existence check was my mistake because I was using && instead of ||.

How do I read this line? [closed]

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

How can I fix this error: System.UnauthorizedAccessException in C#? [closed]

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 3 years ago.
Improve this question
I'm doing a program that create and read .txt files, this function OpenFile should open a selected file but this error appeared. What can I do to the program have authorized access?
void OpenFile()
{
openFileDialog1.ShowDialog();
FileInfo info = new FileInfo(openFileDialog1.FileName);
string directory = info.DirectoryName;
StreamReader str = new StreamReader(directory);
string read = str.ReadLine();
LoadScreenWithText(read);
}
System.UnauthorizedAccessException: Access to the path 'C:\NotePad' was denied'
Im assuming that you are getting and absolute file path in this property "openFileDialog1.FileName"
Try running you program using "Run as administrator" by right clicking on EXE .If you are debugging it with visual studio run VS as an administrator .
Note :Good practice is to always check that whether the file exist or not before further proceeding
Use:
openFileDialog1.ShowDialog();
if(File.Exists(openFileDialog1.FileName){
//Your rest of the code
}

Taking user input from a textbox to create a text file name [closed]

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 9 years ago.
Improve this question
I am using Visual Studio 2013 and C#
I currently have a form which, among other items, has a textbox for the user to enter an id number. I want to be able to 'take' this number and create a text file with the ID number as a file name.
I have been able to write to a file using the OpenFileDialog and Streamwriter, but this requires the user to click the "Save Location" button and browse to a file location, then enter the text for the file they want created.
I would rather have the program create the .txt file based on the id number so that they can just enter their ID and then press enter to start the program.
Is this possible?
Yes it's possible and it's trivial to do. If you want to use your StreamWriter just replace my File.WriteAllText with your StreamWriter code.
button_click_handler(fake args)
{
string fileName = MyTextBox.Text;
File.WriteAllText(basePath + fileName, "file contents");
}
Of course it is possible. The only point not clear in your question is where you want to create this text file and what you want to store inside it.
string fileName = txtForFileName.Text;
// create a path to the MyDocuments folder
string docPath = Environment.GetFolderPath(Environment.SpecialFolders.MyDocuments);
// Combine the file name with the path
string fullPath = Path.Combine(docPath, fileName);
// Note that if the file exists it is overwritten
// If you want to APPEND then use: new StreamWriter(fullPath, true)
using(StreamWriter sw = new StreamWriter(fullPath))
{
sw.WriteLine("Hello world");
}
I think that you could find very useful looking at this MSDN page about Common I/O Tasks
There's a lot of ways to do that.
string thepath = String.Format("{0}{1}{2}","C:\\PutDestinationHere\\",idTextBox.text,".txt");
using(StreamWriter writer = new StreamWriter(thepath))
{
writer.WriteLine();
}

C# - Extract one *.jar file into another one [closed]

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!

Categories