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.
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 have a dlm file and I want to create a .tar.gz file from the content in dlm file. When I am trying to create the file, it is created but when I manually unzip that it is failed. My code is below for creating .tar.gz file, targetFileName is like C:\Folder\xxx.tar.gz:
using (StreamWriter write = new StreamWriter(targetFileName, false, Encoding.Default))
{
write.Write(text.ToString());
write.Close();
}
In the above code text is content from dlm file. Is there anything that I am missing? please help.
try use SharpZipLib from Nuget
using System;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
add method:
private static void CreateTarGZ(string tgzFilename, string innerFilename, string text)
{
var uncompressed = Encoding.UTF8.GetBytes(text);
using (Stream outStream = File.Create(tgzFilename))
{
using (GZipOutputStream gzoStream = new GZipOutputStream(outStream))
{
gzoStream.SetLevel(9);
using (TarOutputStream taroStream = new TarOutputStream(gzoStream, Encoding.UTF8))
{
taroStream.IsStreamOwner = false;
TarEntry entry = TarEntry.CreateTarEntry(innerFilename);
entry.Size = uncompressed.Length;
taroStream.PutNextEntry(entry);
taroStream.Write(uncompressed, 0, uncompressed.Length);
taroStream.CloseEntry();
taroStream.Close();
}
}
}
}
then call:
CreateTarGZ("test.tar.gz", "FileName.txt", "my text");
CreateTarGZ("c:\\temp\\test.tar.gz", "foo-folder\\FileName.txt", "my text");
This is a quick example to create a .tar.gz and .gz file that will include the file that you might be creating using the stream.
Note that I'm using SharpZipLib which you can find in Nuget Package Manager for you project. Then make sure to add reference in your code:
Making tar.gz
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
using System.IO;
using System.Text;
static void Main(string[] args)
{
string text = ".Net is Awesome";
string filename = "D:\\text.txt";
string tarfilename = "D:\\text.tar.gz";
using (StreamWriter write = new StreamWriter(filename, false, Encoding.Default))
{
//Writing a text file
write.Write(text.ToString());
write.Close();
//Creating a tar.gz Stream
Stream TarFileStream = File.Create(tarfilename);
Stream GZStream = new GZipOutputStream(TarFileStream);
TarArchive tarArchive = TarArchive.CreateOutputTarArchive(GZStream);
tarArchive.RootPath = "D:/"; //Setting the Root Path for the archive
//Creating a file entry for the tar archive
TarEntry tarEntry = TarEntry.CreateEntryFromFile(filename);
//Writing the entry in the archive.
tarArchive.WriteEntry(tarEntry, false); //set false to only add the concerned file in the archive.
tarArchive.Close();
}
}
Making only .gz
You can create a method to make it more reusable like:
private static void MakeGz(string targetFile)
{
string TargetGz = targetFile + ".gz";
using (Stream GzStream = new GZipOutputStream(File.Create(TargetGz)))
{
using (FileStream fs = File.OpenRead(targetFile))
{
byte[] FileBuffer = new byte[fs.Length];
fs.Read(FileBuffer, 0, (int)fs.Length);
GzStream.Write(FileBuffer, 0, FileBuffer.Length);
fs.Close();
GzStream.Close();
}
}
}
Then you can call this method whenever you are creating a file to make an archive for the same at the same time like:
MakeGz(filename);
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"))
}
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 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);