This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
how to delete a file?
My application first reads the fields in windows form and then creates a csv file and writes all the fields values in the csv format in it. Then my application reads the csv file and uses it for its further processing. My requirement is that after my application has read the csv file, the file should automatically get deleted(security reasons).
How can i do the above using c# code.
You can use System.IO.File.Delete(FilePath), where FilePath is the file you would like to delete.
Documentation on this
If you concerned about security, perhaps you should look into some alternatives to temporarily writing the data to a file on disk.
Call the System.IO.File.Delete() method, and specify the path to the CSV file as the parameter.
Did you try googling ".NET delete file"? It very quickly points you to System.IO.File.Delete.
Another options besides the System.IO.File.Delete method is to open the file with a special flag. Delete can fail if the file is still in use by another program (or your code, but let's hope not) that hasn't given FileShare.Delete permissions.
An example:
using(var fs = new FileStream(pathToFile, FileMode.Open,
FileAccess.Read, FileShare.None,
1024, FileOptions.DeleteOnClose))
{
// do stuff here
}
// file *may* be deleted here if there are no other
// handles to the file, otherwise it will be deleted
// when all other handles to it are closed, or on
// system restart
That should guarantee that the file gets deleted, if you're expecting other programs to hold handles to the file. If not, it's easier to just use File.Delete.
Related
When reading and following log files on a system where logrotate is installed, it happens at certain times that the existing log file is renamed and a new file with the same name is created. The application will then write new log entries into the new file. When I'm still reading the old file and waiting for new data to be appended there, I'll have to know when the file with that name was replaced so that I can stop reading at the end of the file and restart reading the new file.
My log reader is written in C# (.NET Core 3.1) and will run on Linux. I can use native functions through the Mono.Posix.NETStandard package. But I'm not sure how to do that properly.
Should I fetch the inode number from the file name before I start reading? Or should I compare on other data like the size or time? What's the most robust approach to detecting when the file I've currently opened for reading is replaced?
The solution should ideally still work if the log file was replaced exactly at or around the moment when I opened the file for reading, and also if the old file was very small and the new file will be big from the start (because suddenly a lot happens). I couldn't find any information about this topic at all.
I want to read the content of a file which is opened (and locked?) by a other process.
I tried it with File.ReadAllText() and with new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read)) but both methods trigger a IOException.
For example I can open the file with Notepad++ and the content is shown so I think it must be possible too with c#.
You need to use the FileStream constructor overload that takes a FileShare argument. And pass FileShare.ReadWrite. You can only open the file if you permit write access since the other program already acquired that right. Otherwise the reason that your attempts failed so far, they used FileShare.Read. Can't work, you cannot deny write access because the other program already got that.
Dealing with the program writing to the file while you are reading it is entirely up to you. Results can be quite random. Anything is possible, but in general for a log file you'll get a partially written last line that's trailing behind the actual output of the program, some of which is still in the program's file buffer. A buffer size of 4096 bytes is a common choice.
Wanting to know if it is possible to insert text into the middle of a file using FileStream in .NET/C#. If not, is there another way of doing it? I see the option of Truncate and Append, but obviously that isn't what I'm looking for. I suppose I could open a filestream source, create another destination file and write to it as I see fit, then truncate the source and write back to it from the second file or a large buffer, or delete the source and rename the destination file to the original source filename.
I guess my question is, how is this kind of thing most efficiently and safely done.
No - this is fundamentally a limitation of most file systems.
I would recommend the approach you're suggesting (selective copying from the original file to a new file) but then just rename the files rather than copying back over the top of the original.
If you're happy to have the whole file in memory, you can follow the comment in the question and read the whole file into memory, make the change and then overwrite the existing file - but obviously that doesn't scale as well to very large files. It all depends on the context.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Open file ReadOnly
In my application I am writing some information to Log.txt using Debug.WriteLine(), and I want to provide a form which will show the contents of Log.txt.
But when I try to open the file Log.txt I am getting an exception:
The process cannot access the file 'F:\Rajeev\10-11-2012\Temp\Temp\bin\Debug\Log.txt' because it is being used by another process.
How do I overcome this problem?
And here another issue is, I am able to open the same file using Notepad. Then why can't I open the same file using my application?
The following is the code I am using for specifying the log file:
TextWriterTraceListener tr = new TextWriterTraceListener(System.IO.File.CreateText("Log.txt"));
Debug.Listeners.Add(tr);
Debug.AutoFlush = true;
The following is the code I am using for writing to the log file:
Debug.WriteLine("ERROR: Invalid Username " + s);
The following is the code I am using for opening a log file (which is already opened by "Debug") to show in Log Viewer (a "Form" in my application):
File.Open(LogFilePath, FileMode.Open, FileAccess.Read,FileShare.Read);
This is determined by the permissions the file is opened with. If a program opens the file in any type of exclusive mode, then other programs will have limited or no access.
So you can make sure you don't try to open the file exclusively (you didn't show your code). However, if you don't have the source code for the other program, then you can only hope that that program doesn't open the file exclusively. Otherwise, I don't see what you could do about it except terminate the other program.
EDIT
The following code:
File.Open(LogFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
Says that other files can also read the file that is open, but I believe they can't write to it. So if the other program was writing to the file, that would not be allowed. You could try FileShare.ReadWrite instead but I'm still not seeing where you've indicated if you have source to the other program. Did I just miss it?
I want to view presentation in PowerPoint viewer, ppt file is in a resources. so the problem is that how can i access it and view in PowerPoint viewer.
Here is sample code
Process.Start(#"C:\Program Files\Microsoft Office\Office12\PPTVIEW.exe",**#"e:\presentation.ppt")**;
How can i replace this path by ppt containing in resources?
Actually, what you ask for is a common pattern and there are some related questions and answers here on SO.
Basically what you do in general is the following:
locate the resource in question and open a resource stream to it.
Save the stream to a (temporary) file if your target API cannot deal with streams or byte arrays directly.
Perform whatever operation on the file or directly on the stream/byte array (as I said, if supported).
Eventually remove the temporary file, if any, from step 1.
So, you first extract the PPT file (actually it doesn't really matter that it is a PPT file, could by any file or byte blob for that matter).
string tempFile = Path.GetTempFileName();
using (Stream input = assembly.GetManifestResourceStream("MyPresentation.PPT"))
using (Stream output = File.Create(tempFile))
{
input.CopyTo(output); // Stream.CopyTo() is new in .NET 4.0, used for simplicity and illustration purposes.
}
Then you open it using Process.Start(). You don't need to specify the path to the Powerpoint executable, as PPT should be a registered file extension with either PowerPoint or the PowerPoint Viewer. If you have both installed, you may still want to provide the path to the relevant executable to prevent launching the wrong application. Make sure that you don't hardcode the path though, but try to retrieve it from the registry (or similar, I haven't checked because that gets too specific now).
using (var process = Process.Start(tempFile))
{
process.WaitForExit();
// remove temporary file after use
File.Delete(tempFile);
}
Note: I left out quite some error handling that you might want to add in a real application.