Write to protected file - c#

i wish to write to a protected text file note this content is important.
Can i write to a file to keep it protected i am going to use encryption
but do not wish anyone to read the content of the file. I have tried to
use File.WriteText? but the problem is that the file gets written then
unused so anyone can read the content.
Protection eg. Like the SAM file

In Microsoft Dotnet framework, TextFile attributes are available in c# will enable you to keep the file encrypted and readonly. The write protection can be done using FileIOPermissionAccesss If current user is administrator then he will able to give protect and delete permissions for particular can be given to the file. Below is sample code for adding permission.
var permissionSet = new PermissionSet(PermissionState.None);
var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
permissionSet.AddPermission(writePermission);
if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine("sometext");
}
}
else
{
//perform some recovery action here
}

I too faced similar problem, instead in my case the problem was the
data in my file should be visible to anyone even to the admin user,
and for every time the application runs the previous data should be
replaced by the new one.
Here's my code
string pathfile = #"C:\Users\Public\Documents\Filepath.txt";
if (File.Exists(pathfile))
{
File.Delete(pathfile);
}
if (!File.Exists(pathfile))
{
using (FileStream fs = File.Create(pathfile))
{
Byte[] info = new UTF8Encoding(true).GetBytes("Your Text Here");
fs.Write(info, 0, info.Length);
FileSecurity fsec = File.GetAccessControl(pathfile);
fsec.AddAccessRule(new FileSystemAccessRule("Everyone",
FileSystemRights.FullControl, AccessControlType.Deny));
File.SetAccessControl(pathfile, fsec);
}
}

Related

How to monitor a logfile that seems to be open all the time (much like notepad++ does)?

I'm trying to build a small program to monitor my pfirewall.log, but I can't seem to open it.
I found quite many (simple) answers, that all kinda say
// use FilesystemWatcher
// open FileStream
// read from last position to end
// output new lines
The problem here is: The file seems to always be opened by another process already. I guess that's the windows process writing to the file, since it's getting written to all the time, as Notepad++ shows me.
Which means, Notepad++ can for some reason do what I can not: Read the file despite it being opened already.
I initialize my monitor in the constructor:
public FirewallLogMonitor(string path)
{
if (!File.Exists(path))
throw new FileNotFoundException("Logfile not found");
this.file = path;
this.lastPosition = 0;
this.monitor = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path));
this.monitor.NotifyFilter = NotifyFilters.Size;
}
And try to read the file on monitor.Changed event:
private void LogFileChanged(object sender, FileSystemEventArgs e)
{
using (FileStream stream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader reader = new StreamReader(stream))
{
stream.Seek(this.lastPosition, SeekOrigin.Begin);
var newLines = reader.ReadToEnd();
this.lastPosition = stream.Length;
var filteredLines = filterLines(newLines);
if (filteredLines.Count > 0)
NewLinesAvailable(this, filteredLines);
}
}
It always throws the IOException on new FileStream(...) to tell me the file is already in use.
Since Notepad++ does it, there has to be a way I can do it too, right?
**Edit: ** A button does this:
public void StartLogging()
{
this.IsRunning = true;
this.monitor.Changed += LogFileChanged;
this.monitor.EnableRaisingEvents = true;
}
**Edit2: ** This is not a duplicate of FileMode and FileAccess and IOException: The process cannot access the file 'filename' because it is being used by another process, since that one assumes I have control over the writing process. Will try the other suggestions, and report back with results.
If i understand your question you can use the notepad++ itself with a plugin to monitor you need to go to:
plugins -> Document Moniter -> Start to monitor
if you dont have this plugin you can download it here:
http://sourceforge.net/projects/npp-plugins/files/DocMonitor/

Write on a network folder from android (Xamarin) System.UnauthorizedAccessException

I created a android app to create a stockage list by capturing code bars, the idea is to write a csv file in to a network folder, because I want the app to run as much offline as it's possible.
Currently my code looks like:
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string filename = Path.Combine(path, "stock.csv");
using (var streamWriter = new StreamWriter(filename, true))
using (var writer = new CsvWriter(streamWriter))
{
foreach (var item in articulos)
{
writer.WriteField(item.codbar);
writer.WriteField(item.reference);
writer.WriteField(item.quantity);
writer.NextRecord();
}
}
string path2 = #"\\Desktop-jce8pl5\csv\stock.csv";
File.Copy(filename, path2,true);
But I keep geting a System.UnauthorizedAccessException
I tried to enter directly to the file from another computer and there
is no problem.
I give full permission to "all" and "network"
I tried directly with IP I tried not to copy, just to create
string path = #"\\Desktop-jce8pl5\csv\stock.csv";
FileStream fs = null;
if (File.Exists(path))
{
fs = File.Open(path, FileMode.Append);
}
else
{
fs = File.Create(path);
}
But there is no way.
Any help?
Thanks.
As #RobertN sugested, I tried to connect with EX File Ex and detected that I was unable to, so I checked the windows 10 general configuration to shared folders and it was only enabled to auth users.
I changed that, then I start with the cifsmanager but on that moment we decided that, if the user has access to local network he will most sure have acces to internet, so I will send the file by email.

Using StreamReader / StreamWriter to grab logs causes program to cease responding

I'm attempting to use StreamReader and StreamWriter to grab a temporary output log (.txt format) from another application.
The output log is always open and constantly written to.
Unhelpfully if the application closes or crashes, the log file ends up deleted - hence the need for a tool that can grab the information from this log and save it.
What my program currently does is:
Create a new .txt file, and stores the path of that file as the
string "destinationFile".
Finds the .txt log file to read, and stores the path of that file as
the string "sourceFile"
It then passes those two strings to the method below.
Essentially I'm trying to read the sourceFile one line at a time.
Each time one line is read, it is appended to destinationFile.
This keeps looping until the sourceFile no longer exists (i.e. the application has closed or crashed and deleted its log).
In addition, the sourceFile can get quite big (sometimes 100Mb+), and this program may be handling more than one log at a time.
Reading the whole log rather than line by line will most likely start consuming a fair bit of memory.
private void logCopier(string sourceFile, string destinationFile)
{
while (File.Exists(sourceFile))
{
string textLine;
using (var readerStream = File.Open(sourceFile,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
using (var reader = new StreamReader(readerStream))
{
while ((textLine = reader.ReadLine()) != null)
{
using (FileStream writerStream = new FileStream(destinationFile,
FileMode.Append,
FileAccess.Write))
using (StreamWriter writer = new StreamWriter(writerStream))
{
writer.WriteLine(textLine);
}
}
}
}
}
The problem is that my WPF application locks up and ceases to respond when it reaches this code.
To track down where, I put a MessageBox just before the writerStream line of the code to output what the reader was picking up.
It was certainly reading the log file just fine, but there appears to be a problem with writing it to the file.
As soon as it reaches the using (FileStream writerStream = new FileStream part of the code, it stops responding.
Is using the StreamWriter in this manner not valid, or have I just gone and dome something silly in the code?
Am also open to a better solution than what I'm trying to do here.
Simply what I understand is you need to copy a file from source to destination which may be deleted at any time.
I'll suggest you to use FileSystemWatcher to watch for source file changed event, then just simply copy the whole file from source to destination using File.Copy.
I've just solved the problem, and the issue was indeed something silly!
When creating the text file for the StreamWriter, I had forgotten to use .Dispose();. I had File.Create(filename); instead of File.Create(filename).Dispose(); This meant the text file was already open, and the StreamWriter was attempting to write to a file that was locked / in use.
The UI still locks up (as expected), as I've yet to implement this on a new thread as SteenT mentioned. However the program no longer crashes and the code correctly reads the log and outputs to a text file.
Also after a bit of refinement, my log reader/writer code now looks like this:
private void logCopier(string sourceFile, string destinationFile)
{
int num = 1;
string textLine = String.Empty;
long offset = 0L;
while (num == 1)
{
if (File.Exists(sourceFile))
{
FileStream stream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (new StreamReader(stream))
{
stream.Seek(offset, SeekOrigin.Begin);
TextReader reader2 = new StreamReader(stream);
while ((textLine = reader2.ReadLine()) != null)
{
Thread.Sleep(1);
StreamWriter writer = new StreamWriter(destinationFile, true);
writer.WriteLine(textLine);
writer.Flush();
writer.Close();
offset = stream.Position;
}
continue;
}
}
else
{
num = 0;
}
}
}
Just putting this code up here in case anyone else is looking for something like this. :)

Getting current log file content in Enterprise Library Logging

I've set up the Enterprise Library Logging Application Block to log in a file called 'app.log' residing in the execution path of my application. This application is a Windows service which runs a configuration website on top of it, where I now want to show the contents of the log file.
Getting the log file was a rather easy task:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var logSection = config.GetSection("loggingConfiguration") as LoggingSettings;
var lookup = logSection.TraceListeners
.Where(x => x is RollingFlatFileTraceListenerData).FirstOrDefault() as RollingFlatFileTraceListenerData;
if(lookup != null) {
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, lookup.FileName);
return File.ReadAllText(_logFilePath);
}
However, the RollingFlatFileTraceListener I've set up constantly BLOCKS the file I want to read from. Is there any possibility to access it?
Check this answer. That this is not the default behavior for File.ReadAllText is beyond me...
using (var logFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var logFileReader = new StreamReader(logFileStream))
{
return logFileReader.ReadToEnd();
}
Also note that you are mixing filePath and _logFilePath.

Save text from C# textbox to txt file. (Creating a new txt file everytime without same name of files)

I would like to get the text from the textbox of my C# application into a .txt file. The issue I have is that the current saved file will overwrite the previously saved file. My current code is:
string log = #"C:\log.txt";
using (FileStream fs = new FileStream(log, FileMode.Create)) {
using (StreamWriter sw = new StreamWriter(fs)) {
foreach(string line in Textbox1.Lines)
sw.Write(line + sw.NewLine);
}
}
Is it possible to save the txt file but without it overwriting the previously saved file? Can someone help me with this.. Thanks
I belive you are talking about appending the lines:
using(FileStream fs = new FileStream(log, FileMode.Append)) {
//...
}
Try this
string log = #"C:\log"+ DateTime.Now.ToString("dd-MM-yyyy hh-mm-ss") +".txt";
Just add a time stamp to the file name
If you want to write to the same file you could use FileMode.Append:
FileStream fs = new FileStream(log, FileMode.Append)
Take care if you're in a threaded environment (ie. asp.net which I suspect since you're talking about downloads), regarding file locks and such
Try
string log = #"C:\log"+ DateTime.Now.ToString("yyyyMMddHHmmssfffffff")+".txt";
this gives precision up to ten millionths of a second
This should help:
string log = #"C:\log.txt";
int intCounter = 0;
While(File.Exists(log))
{
log = #"C:\log"+ intCounter.ToString() +".txt";
}
try this ==>
string log = #"C:\log"+ new Guid().ToString("N") +".txt";

Categories