I wrote a program which reads a csv file, makes some changes and writes to a new csv file.
I want the user to be able to select the csv file to be read from their directory using an open file dialog box on a windows form.
So far I have been able to write some of the code so that the user can look for the file but I am not sure on how to link the file the user has chosen to the steamreader.
This is the code to read and write the csv file
try
{
using (StreamWriter sw = new StreamWriter("X:/PublishedSoftware/Data/NEWPYAEGON1PENSION.csv"))
{
using (StreamReader sr = new StreamReader(""))
{
This is the code for the open file dialog box
private void btnFindAegonFile_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "csv files(*.csv)|*.csv|All files(*.*)|*.*";
openFileDialog1.FileName = "Browse for the AEGON file.";
DialogResult result = openFileDialog1.ShowDialog();
txtFindAegonFile.Text = this.openFileDialog1.FileName;
If you have the file name:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = this.openFileDialog1.FileName;
...
}
You can read the contents using the stream reader (in the place of ...):
using (StreamReader sr = new StreamReader(fileName))
Or read the contents directly:
string input = File.ReadAllText(fileName);
Here is a snippet of how to go from a file name to a StreamReader:
var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (var sr = new StreamReader(fs))
{
...
}
You have to complete the FileOpen Dialog code snippet by passing the file path to StreamWriter, like:
using (StreamWriter sw = new StreamWriter(fileName));
// ... open the file w/StreaWriter
Use openFileDialog1's FileOK event to know when the user has selected a valid file. You can then recive the file path from openFileDialog1.FileName.
I got it working I used:
string readfilename = txtFindAegonFile.Text;
try
{
using (StreamReader sr = new StreamReader(readfilename))
using (StreamWriter sw = new StreamWriter("X:/PublishedSoftware/Data/NEWPYAEGON1PENSION.csv"))
}
Related
I'm making a text editor using fastColoredTextbox. I have a button that allows you to save your text onto your pc. The problem is that it throws an exception when the user tries to save the file as a file that already exists, instead of overwriting the file.
This is my code.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(fastColoredTextBox1.Text);
}
}
How would I go about making it overwrite the file if it already exists?
Maybe this could help you:
sw = new StreamWriter(path, true);
sw.WriteLine(line);
https://learn.microsoft.com/es-es/dotnet/api/system.io.streamwriter.-ctor?view=net-6.0#system-io-streamwriter-ctor(system-string-system-boolean)
I changed up my code a bit and ended up going with this, which somehow got it to work.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Stream s = saveFileDialog1.OpenFile();
StreamWriter sw = new StreamWriter(s);
sw.Write(fastColoredTextBox1.Text);
sw.Close();
}
I want to rewrite text file using StreamWriter. but when StreamWriter uses stream (like following code), the text will append to file.
StreamWriter sw = new StreamWriter(fstream);
sw.Write(text);
sw.Close();
i must use Stream in code because of that file share limitation
FileMode.Create ll create a new file. If the file excists, it ll show exception. Use FileMode.Truncate.
string txt="your text";
using (FileStream fs = new FileStream(#"C:\Users\rajesh.kumar\Desktop\test123.txt", FileMode.Truncate))
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.Write("txt");
}
}
If you use file stream, set FileMode:
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.Write(textToAdd);
}
}
I'm working on WCF services application. I want to create a file in one of my function
so now this time I'm doing like this. First I go to directory creates a file then i do read/write.
string path = AppDomain.CurrentDomain.BaseDirectory;
path += "Emp_data\\json_data.json";
StreamReader reader = new StreamReader(path);
StreamWriter writer = new StreamWriter(path);
I know I'm doing this in wrong way. Please suggest me a better way so that if there in no file and folder It will create automatically.
Nothing extra happens with creating a file in WCF so you can do that like this
string path = AppDomain.CurrentDomain.BaseDirectory;
String dir = Path.GetDirectoryName(path);
dir += "\\Emp_data";
string filename = dir+"\\Json_data.json";
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir); // inside the if statement
FileStream fs = File.Open(filename,FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader reader = new StreamReader(fs);
Creating a file has nothing to do with WCF. Doing so is the same regardless of the context. I prefer to use the methods on the static File class.
To create a file is simple.
string path = AppDomain.CurrentDomain.BaseDirectory;
path += "Emp_data\\json_data.json";
using(FileStream fs = System.IO.File.Create(path))
{
}
If you just want to write data, you can do...
File.WriteAllText(path, contentsIWantToWrite);
Your problem is not related to WCF services in general.
Something like this will work (if you have write access to the file):
String dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir)
using (FileStream fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
// work with fs to read from and/or write to file, maybe this
using (StreamReader reader = new StreamReader(fs))
{
using (StreamWriter writer = new StreamWriter(fs))
{
// need to sync read and write somehow
}
}
}
I'm working on an encryption program in C# (Windows Forms) and one of the options I'd like to add is that the user will be able to choose an existing text (.txt) file, and the program would make a new file which is the file chosen, but encrypted (without making any changes in the original file).
I though about making a copy of the original file and then encrypting the new file, but I have no clue how to do it.
Please tell me how to do it.
Thanks a lot in advance!
StreamReader/StreamWriter for loading and saving the file.
StreamReader:
string unencryptedText;
private void ReadTextFile()
{
using (StreamReader reader = new StreamReader("file.txt"))
{
unencryptedText= reader.ReadToEnd();
}
}
StreamWriter
using (StreamWriter writer = new StreamWriter("encryptedFile.txt", true))
{
writer.Write(encryptedText);
}
Encryption: Simple insecure two-way "obfuscation" for C#
Update
Chose Directory where to save encrypted file(only Directory)
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(fbd.SelectedPath+"\\encryptedFile.txt", true))
{
writer.Write(encryptedText);
}
}
Chose Directory and FileName
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(sfd.FileName, true))
{
writer.Write(encryptedText);
}
}
Use System.IO.StreamReader and System.IO.StreamWriter to read and write from text files.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx
using (StreamReader sr = new StreamReader(filePath))
{
fileContents = sr.ReadToEnd();
}
string encryptedContents = Encrypt(fileContents);
using (StreamWriter sw = new StreamWriter(destinationPath))
{
sw.Write(encryptedContents);
}
File.Copy(pathX,pathY)
Will copy the file from path X to path Y.
The next thing is to write the encrypted text to the copied file:
File.WriteAllText(pathY,textToWrite)
I can also say you will learn more if you read msdn examples.
Everything you look for is there.
I am trying it too much time but can not achieve the goal. File is opened but its opened in write mode.
Code-
in txtpath.text, I am passing the path of the text:
System.IO.FileInfo fileObj= new System.IO.FileInfo(txtPath.Text);
fileObj.Attributes = System.IO.FileAttributes.ReadOnly;
System.Diagnostics.Process.Start(fileObj.FullName);
use the File.OpenRead method
string sFilename = "myfile.txt";
FileStream SR = File.OpenRead(sFilename);
Opening a file to only read it's contents:
// Open the stream and read it back.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
More about File.OpenRead: http://msdn.microsoft.com/en-us/library/system.io.file.openread.aspx
Setting a file's ReadOnly attribute and executing it:
File.SetAttributes(txtPath.Text, File.GetAttributes(txtPath.Text) | FileAttributes.ReadOnly);
System.Diagnostics.Process.Start(txtPath.Text);