| | |
create and write into INFO File from C#
Please support our C# advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
Join Date: Nov 2007
Posts: 84
Reputation:
Solved Threads: 0
Hi there,
I need to create an INFO file in the setup of an application, and within the application I need to write on that file ,
actually I did some google, but I did not find article that discuss what I need ,
specifically if the writing operation , which may need encrypting decrypting .
Please if any has any ideas or even keywords that could help , I am appreciating ,
Thanks in advance
I need to create an INFO file in the setup of an application, and within the application I need to write on that file ,
actually I did some google, but I did not find article that discuss what I need ,
specifically if the writing operation , which may need encrypting decrypting .
Please if any has any ideas or even keywords that could help , I am appreciating ,
Thanks in advance
there's always something to learn
•
•
Join Date: Nov 2006
Posts: 436
Reputation:
Solved Threads: 72
There are many ways to do this task, and I will let the others on this board give you the standard way(s) of doing this.
One method I have been using lately is quite simple, and does not require you to learn XML syntax or file IO management, or any of that stuff.
I drop a Dataset component on the main application.
I setup at least one table with the kind of information I want to persist. Briefcase Model.
When the application starts up, it will look for a file, and if found, the dataset will load it. Now all of my configuration information is found in the dataset. If I need to make changes to the configuration, I just make the changes to the dataset contents. When the application closes, I save the dataset to my filename.
One additional advantage is that I do not have to create a bunch of variables to maintain configuration information... It is already in my dataset along with Names, Types, etc.
The advantage of this method is that I can store multiple configurations, multiple types of configuration information, Bitmaps, documents, anything you want to stick into a DataTable.
Another advantage is that I can filter the configuration information for the currently logged on user (let each user customize the application to meet their needs).
Why read and write XML when you can just let the Dataset component do it for you.
Dataset XML files are in plain text, so if you store sensitive information, I suggest you encrypt it before sticking it in the Dataset.
// Jerry
One method I have been using lately is quite simple, and does not require you to learn XML syntax or file IO management, or any of that stuff.
I drop a Dataset component on the main application.
I setup at least one table with the kind of information I want to persist. Briefcase Model.
When the application starts up, it will look for a file, and if found, the dataset will load it. Now all of my configuration information is found in the dataset. If I need to make changes to the configuration, I just make the changes to the dataset contents. When the application closes, I save the dataset to my filename.
One additional advantage is that I do not have to create a bunch of variables to maintain configuration information... It is already in my dataset along with Names, Types, etc.
The advantage of this method is that I can store multiple configurations, multiple types of configuration information, Bitmaps, documents, anything you want to stick into a DataTable.
Another advantage is that I can filter the configuration information for the currently logged on user (let each user customize the application to meet their needs).
Why read and write XML when you can just let the Dataset component do it for you.
Dataset XML files are in plain text, so if you store sensitive information, I suggest you encrypt it before sticking it in the Dataset.
// Jerry
•
•
Join Date: Nov 2006
Posts: 436
Reputation:
Solved Threads: 72
The use of the Dataset allows you to save itself as an XML file to disk.
This means that the next time you load your application, the dataset can repopulate itself by loading the XML file.
This technique allows you to store and retrieve any kind of configuration information you could ever need. You can load multiple tables in the dataset, and all of them are saved with one line of code to save the entire dataset as an XML file.
Now you can use full flown database functionality to manage, find, etc any of your configuration information...
This Dataset is not connected to a real database... it is just a managed XML container that you can store connection strings, Bitmaps, a user supplied Icon for your app.. Just about anything you want to store in a configuration media.
// Jerry
This means that the next time you load your application, the dataset can repopulate itself by loading the XML file.
This technique allows you to store and retrieve any kind of configuration information you could ever need. You can load multiple tables in the dataset, and all of them are saved with one line of code to save the entire dataset as an XML file.
C# Syntax (Toggle Plain Text)
// Saving a dataset to Disk string FileName = "MyFileName.xml"; // VrfDataSet is my Configuration Dataset VrfDataSet.WriteXml(FileName, XmlWriteMode.WriteSchema);
C# Syntax (Toggle Plain Text)
// Loading a dataset string FileName = "MyFileName.xml"; if( File.Exists(FileName) ) { VrfDataSet.Clear(); try { VrfDataSet.ReadXml(Filename); . . .
Now you can use full flown database functionality to manage, find, etc any of your configuration information...
This Dataset is not connected to a real database... it is just a managed XML container that you can store connection strings, Bitmaps, a user supplied Icon for your app.. Just about anything you want to store in a configuration media.
// Jerry
Last edited by JerryShaw; May 1st, 2008 at 8:45 pm.
•
•
Join Date: Nov 2006
Posts: 436
Reputation:
Solved Threads: 72
Since no one has told you the standard ways yet..
Look at Property Settings
The next options are using home grown XML files, INI files or the Registry.
// Jerry
Look at Property Settings
The next options are using home grown XML files, INI files or the Registry.
// Jerry
•
•
Join Date: Nov 2007
Posts: 84
Reputation:
Solved Threads: 0
Thanks again Jerry,
it seems that I did not get, but now it is ok ,
just to be clear , an info file is not an ordinary file that is represented by an IO, but there is something I do not get yet , is the the file saved as .info?
if I am not wrong , there are files of that extension, aren't they?
I need to understand it more so I can take my ease to use the way I want .
all what I want is to save 2 words in a file but I want it to be secure (can not be seen) a text file is not appropriate
is INI files have the same idea
it seems that I did not get, but now it is ok ,
just to be clear , an info file is not an ordinary file that is represented by an IO, but there is something I do not get yet , is the the file saved as .info?
if I am not wrong , there are files of that extension, aren't they?
I need to understand it more so I can take my ease to use the way I want .
all what I want is to save 2 words in a file but I want it to be secure (can not be seen) a text file is not appropriate
•
•
•
•
The next options are using home grown XML files, INI files or the Registry.
// Jerry
there's always something to learn
•
•
Join Date: Nov 2007
Posts: 84
Reputation:
Solved Threads: 0
•
•
•
•
Please explain "an info file is not an ordinary file that is represented by an IO" ?
// Jerry
I meant by ( .info ) file , a file that it's extension is .info , this is first ,
then ordinary file , I mean a file that is opened and be written on directly , ( for example txt file) , when I read the link you thankfully have sent me, I did not understand what the connection to the .info file could be , it seems that I had completely different idea about the topic,
any other explanations !,
thanks
there's always something to learn
•
•
Join Date: Nov 2006
Posts: 436
Reputation:
Solved Threads: 72
Knowledgelover,
Let’s re-visit your original request.
You want to have a means of storing and retrieving secured setup information for your application.
To be persistent, it means either writing something to the registry or to a file (I will make the distinction even though the registry is also a file).
Don't get hung-up on file extensions. There is no standard for "info" files that I am aware of. IOW there is no commonly used association with any particular viewer for a file with this extension.
The easiest approach is to use the Properties | Settings item in the solution explorer.
Expand the Properties tree item in the solution explorer.
Select (double-click) the Settings.settings tree node.
A grid will appear.
I will assume that you want to strore two pieces of information. I will assume the first is named “UserName”, and the second will be “Password”.
In the first available row in the settings grid, enter the name of the variable “UserName”.
Enter a new row and set the name to “Password”.
The settings file will be saved as the name of your executable with the extension of “.config”. Example MyApplication.exe will have a file named MyApplication.exe.config
This config file is your info file. It will contain XML.
In your c# code you can read and write this information.
Nothing special to do.
Now if you also want to save that information as encrypted then you need to do something extra. Below is a full blown Encrypting Decrypting class, and the button events redone to reflect the use of Encrypting and Decrypting the information.
If this solved your problem, or answered your question , please mark this topic as solved.
Note to other readers: This is not an example of how you should store user names and passwords in a file. First you shoud make every attempt to NOT store that kind of information. You would never want to set a hard coded key as done in this example. There are many other ways to get a key, and encrypting/decrypting.
// Jerry
shawjh@meadowcrk.com
Let’s re-visit your original request.
You want to have a means of storing and retrieving secured setup information for your application.
To be persistent, it means either writing something to the registry or to a file (I will make the distinction even though the registry is also a file).
Don't get hung-up on file extensions. There is no standard for "info" files that I am aware of. IOW there is no commonly used association with any particular viewer for a file with this extension.
The easiest approach is to use the Properties | Settings item in the solution explorer.
Expand the Properties tree item in the solution explorer.
Select (double-click) the Settings.settings tree node.
A grid will appear.
I will assume that you want to strore two pieces of information. I will assume the first is named “UserName”, and the second will be “Password”.
In the first available row in the settings grid, enter the name of the variable “UserName”.
Enter a new row and set the name to “Password”.
The settings file will be saved as the name of your executable with the extension of “.config”. Example MyApplication.exe will have a file named MyApplication.exe.config
This config file is your info file. It will contain XML.
In your c# code you can read and write this information.
C# Syntax (Toggle Plain Text)
private void button1_Click(object sender, EventArgs e) { string un = Properties.Settings.Default.UserName; string up = Properties.Settings.Default.Password; MessageBox.Show(string.Format("UserName={0}\r\nPassword={1}",un,up)); } private void button2_Click(object sender, EventArgs e) { Properties.Settings.Default.UserName = "Test user name"; Properties.Settings.Default.Password = "12345"; Properties.Settings.Default.Save(); }
Now if you also want to save that information as encrypted then you need to do something extra. Below is a full blown Encrypting Decrypting class, and the button events redone to reflect the use of Encrypting and Decrypting the information.
C# Syntax (Toggle Plain Text)
private void button1_Click(object sender, EventArgs e) { string un = Properties.Settings.Default.UserName; string up = Properties.Settings.Default.Password; MessageBox.Show(string.Format("UserName={0}\r\nPassword={1}" ,EncDec.Decrypt(un,"MySecretPrivatePassword") ,EncDec.Decrypt(up,"MySecretPrivatePassword") )); } private void button2_Click(object sender, EventArgs e) { string un = EncDec.Encrypt("test user name", "MySecretPrivatePassword"); string up = EncDec.Encrypt("12345", "MySecretPrivatePassword"); Properties.Settings.Default.UserName = un; Properties.Settings.Default.Password = up; Properties.Settings.Default.Save(); } using System.Security.Cryptography; using System.IO; public class EncDec { /// <summary> /// Encrypt a byte array into a byte array using a key and an IV /// </summary> /// <param name="clearData"></param> /// <param name="Key"></param> /// <param name="IV"></param> /// <returns></returns> public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) { // Create a MemoryStream that is going to accept the encrypted bytes MemoryStream ms = new MemoryStream(); // Create a symmetric algorithm. // We are going to use Rijndael because it is strong and available on all platforms. // You can use other algorithms, to do so substitute the next line with something like // TripleDES alg = TripleDES.Create(); Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = IV; CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); // Write the data and make it do the encryption cs.Write(clearData, 0, clearData.Length); // Close the crypto stream (or do FlushFinalBlock). // This will tell it that we have done our encryption and there is no more data coming in, // and it is now a good time to apply the padding and finalize the encryption process. cs.Close(); // Now get the encrypted data from the MemoryStream. // Some people make a mistake of using GetBuffer() here, which is not the right way. byte[] encryptedData = ms.ToArray(); return encryptedData; } /// <summary> /// Encrypt a string into a string using a password /// Uses Encrypt(byte[], byte[], byte[]) /// </summary> /// <param name="clearText"></param> /// <param name="Password"></param> /// <returns></returns> public static string Encrypt(string clearText, string Password) { byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return Convert.ToBase64String(encryptedData); } /// <summary> /// Encrypt bytes into bytes using a password /// Uses Encrypt(byte[], byte[], byte[]) /// </summary> /// <param name="clearData"></param> /// <param name="Password"></param> /// <returns></returns> public static byte[] Encrypt(byte[] clearData, string Password) { PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16)); } /// <summary> /// Encrypt a file into another file using a password /// </summary> /// <param name="fileIn"></param> /// <param name="fileOut"></param> /// <param name="Password"></param> public static void Encrypt(string fileIn, string fileOut, string Password) { // First we are going to open the file streams FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read); FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write); // Then we are going to derive a Key and an IV from the Password and create an algorithm PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), CryptoStreamMode.Write); int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int bytesRead; do { bytesRead = fsIn.Read(buffer, 0, bufferLen); // read a chunk of data from the input file cs.Write(buffer, 0, bytesRead); // encrypt it } while (bytesRead != 0); cs.Close(); // this will also close the unrelying fsOut stream fsIn.Close(); } /// <summary> /// Decrypt a byte array into a byte array using a key and an IV /// </summary> /// <param name="cipherData"></param> /// <param name="Key"></param> /// <param name="IV"></param> /// <returns></returns> public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV) { MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = IV; CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write); // Write the data and make it do the decryption cs.Write(cipherData, 0, cipherData.Length); cs.Close(); byte[] decryptedData = ms.ToArray(); return decryptedData; } /// <summary> /// Decrypt a string into a string using a password /// Uses Decrypt(byte[], byte[], byte[]) /// </summary> /// <param name="cipherText"></param> /// <param name="Password"></param> /// <returns></returns> public static string Decrypt(string cipherText, string Password) { byte[] cipherBytes = Convert.FromBase64String(cipherText); PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return System.Text.Encoding.Unicode.GetString(decryptedData); } /// <summary> /// Decrypt bytes into bytes using a password /// Uses Decrypt(byte[], byte[], byte[]) /// </summary> /// <param name="cipherData"></param> /// <param name="Password"></param> /// <returns></returns> public static byte[] Decrypt(byte[] cipherData, string Password) { // We need to turn the password into Key and IV. // We are using salt to make it harder to guess our key using a dictionary attack - // trying to guess a password by enumerating all possible words. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); return Decrypt(cipherData, pdb.GetBytes(32), pdb.GetBytes(16)); } /// <summary> /// Decrypt a file into another file using a password /// </summary> /// <param name="fileIn"></param> /// <param name="fileOut"></param> /// <param name="Password"></param> public static void Decrypt(string fileIn, string fileOut, string Password) { PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read); FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write); try { Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write); try { int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int bytesRead; do { bytesRead = fsIn.Read(buffer, 0, bufferLen); cs.Write(buffer, 0, bytesRead); } while (bytesRead != 0); } finally { if (cs != null) { cs.Close(); } // this will also close the unrelying fsOut stream } } finally { if (fsOut != null) { fsOut.Close(); } if (fsIn != null) { fsIn.Close(); } } } }
If this solved your problem, or answered your question , please mark this topic as solved.
Note to other readers: This is not an example of how you should store user names and passwords in a file. First you shoud make every attempt to NOT store that kind of information. You would never want to set a hard coded key as done in this example. There are many other ways to get a key, and encrypting/decrypting.
// Jerry
shawjh@meadowcrk.com
![]() |
Similar Threads
- Postback URL ? (ASP.NET)
- Help on a reading from a file programming (Java)
- Get data out of excel file stored as an image (MS SQL)
- create pdf or word file from within c# (C#)
- Custom Class - File I/O (C++)
- Write to Screen and File{I-O question} (C++)
- File operations (C)
- create, write & read file to/from folder (C++)
- Please help with File I/O (Java)
- Quick Reference for Linux Commands (Getting Started and Choosing a Distro)
Other Threads in the C# Forum
- Previous Thread: Text box do not execute "\n"
- Next Thread: i need help!!!
Views: 5108 | Replies: 9
| Thread Tools | Search this Thread |
Tag cloud for C#
.net access ado.net algorithm array barchart bitmap box broadcast buttons c# chat check checkbox class client color combobox control conversion csharp custom database datagrid datagridview dataset datetime degrees development draganddrop drawing encryption enum event excel file files form format forms ftp function gdi+ httpwebrequest image index install java label list listbox listener login mandelbrot math mouseclick mysql networking object operator oracle path photoshop picturebox pixelinversion post prime programming radians regex remote remoting resource richtextbox save saving serialization server sleep socket sql statistics stream string table tcp text textbox thread time timer treeview update validation visualstudio webbrowser windows winforms wpf xml





