Check file accessibility .NET Core - c#

I would like to check if file is accessible.
I list file using
IFileProvider provider = new PhysicalFileProvider(_settings.appSettings.sourceDirectory);
var files = provider.GetDirectoryContents("");
Then i got a list of IFileInfo and not FileInfo
I would like to check if the file is not in use or in creation by a scanner or something like that (The program is a directory scanner (in the scanner reception folder) which send these files to a Web API)
In .NET 4.5 I could do this :
public static bool IsFileLocked(this FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (stream != null)
stream.Close();
}
return false;
}
But i can't do this in .NET Core 2 or 1
I can use the stream reader, but I need performance to read a maximum of files (this directory can get 1000 files every 30 seconds)
Thanks

Related

Is there a way to check that a file is in use

Using c#, is there a way to check that a file is in use. More specifically, I need a way to monitor a directory of .wav files and see which sound file has been loaded.
Note. It can be loaded by different applications.
I've had a look at Core Audio.. but I cannot seem to find an answer there.
I've also tried to code that if the file is locked but that also doesnt provide a solution. So if you know of a way to determine which sound file (.wav) is currently being played, please comment.
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
Here is the reference link : File is in Use
Hope it helps.

c# check if file is opened or being copied

I have a problem that is driving me mad. Maybe you could help ;)
I'm tracking file changes on the folder with FileSystemWatcher and copy changed files to another folder. I don’t want to copy the file until it is done being saved. I cannot find a solution that works at the same time for all 3 scenarios below:
1) New file being copied into the folder
2) Existing file being overwritten by copying new one
3) File is opened by another process (i.e. Word)
I have tried IsFileLocked method from the thread below.
c# check if file is open
It will work for copying but the problem is that function will always return TRUE for opened OFFICE files (maybe for some others as well).
I also tried to check in the loop if the file size changes but it’s seems to be impossible as FileInfo.Length always return the target size (even though file is still being copied).
I'm using that function to check if file is in use
public static bool IsFileLocked(string path)
{
FileInfo fileInfo = new FileInfo(path);
FileStream stream = null;
try
{
stream = fileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (UnauthorizedAccessException)
{
// file created with readonly flag
return false;
}
catch (FileNotFoundException)
{
return false;
}
catch (IOException ex)
{
int errorCode = Marshal.GetHRForException(ex) & ((1 << 16) - 1);
bool islocked = errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
return islocked;
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
//file is not locked
return false;
}
Do you know how to distinguish if it's opened by some application or being copied?

c# Detect if file has finished being written

I am writing a PowerPoint add-in that FTPs a file that has been converted to a WMV.
I have the following code which works fine:
oPres.CreateVideo(exportName);
oPres.SaveAs(String.Format(exportPath, exportName),PowerPoint.PpSaveAsFileType.ppSaveAsWMV,MsoTriState.msoCTrue);
But this kicks off a process within PP which does the file conversion and it immediately goes to the next line of code before the file has finished being written.
Is there a way to detect when this file has finished being written so I can run the next line of code knowing that the file has been finished?
When a file is being used it is unavailable, so you could check the availability and wait until the file is available for use. An example:
void AwaitFile()
{
//Your File
var file = new FileInfo("yourFile");
//While File is not accesable because of writing process
while (IsFileLocked(file)) { }
//File is available here
}
/// <summary>
/// Code by ChrisW -> http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use
/// </summary>
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}

How to save a file without prompting the user for a name/path?

I'm trying to open a stream to a file.
First I need to save a file to my desktop and then open a stream to that file.
This code works well (from my previous project) but in this case, I don't want to prompt the user to pick the save location or even the name of the file. Just save it and open the stream:
Stream myStream;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
PdfWriter.GetInstance(document, myStream);
Here's my code for the newer project (the reason for this question):
namespace Tutomentor.Reporting
{
public class StudentList
{
public void PrintStudentList(int gradeParaleloID)
{
StudentRepository repo = new StudentRepository();
var students = repo.FindAllStudents()
.Where(s => s.IDGradeParalelo == gradeParaleloID);
Document document = new Document(PageSize.LETTER);
Stream stream;
PdfWriter.GetInstance(document, stream);
document.Open();
foreach (var student in students)
{
Paragraph p = new Paragraph();
p.Content = student.Name;
document.Add(p);
}
}
}
}
Use Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) to get the desktop directory.
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
"MyFile.pdf");
using(var stream = File.OpenWrite(fileName))
{
PdfWriter.GetInstance(document, stream);
}
// However you initialize your instance of StudentList
StudentList myStudentList = ...;
using (FileStream stream = File.OpenWrite(#"C:\Users\me\Desktop\myDoc.pdf")) {
try {
myStudentList.PrintStudentList(stream, gradeParaleloID);
}
finally {
stream.Close();
}
}
You should pass the stream into your method:
public void PrintStudentList(Stream stream, int gradeParaleloID) { ... }
EDIT
Even though I hard coded a path above, you shouldn't do that, use something like this to get the path to your desktop:
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
If this is a local (e.g. Windows/console) application just make the stream a FileStream to whatever path you want (check this for info on how to get the desktop folder path). If the user running the application has write permitions to that file it will be created/saved there.
If this is a web (e.g. ASP.Net) application you won't be able to save the file directly in the client machine without prompting the user (for security reasons).
Stream myStream = new FileStream(#"c:\Users\[user]\Desktop\myfile.dat", FileMode.OpenOrCreate);
Your FileMode may differ depending on what you're trying to do. Also I wouldn't advise actually using the Desktop for this, but that's what you asked for in the question. Preferably, look into Isolated Storage.

Is there a better way than this to find out if an IsolatedStorage file exists or not?

I'm using IsolatedStorage in a Silverlight application for caching, so I need to know if the file exists or not which I do with the following method.
I couldn't find a FileExists method for IsolatedStorage so I'm just catching the exception, but it seems to be a quite general exception, I'm concerned it will catch more than if the file doesn't exist.
Is there a better way to find out if a file exists in IsolatedStorage than this:
public static string LoadTextFromIsolatedStorageFile(string fileName)
{
string text = String.Empty;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName,
FileMode.Open, isf))
{
using (StreamReader sr = new StreamReader(isfs))
{
string lineOfData = String.Empty;
while ((lineOfData = sr.ReadLine()) != null)
text += lineOfData;
}
}
return text;
}
catch (IsolatedStorageException ex)
{
return "";
}
}
}
From the "manual" (.net framework 2.0 Application Development Foundation):
Unlike the application programming interface (API) for files stored arbitrarily
in the file system, the API for files in Isolated Storage does not support checking
for the existence of a file directly like File.Exists does. Instead, you need to ask the
store for a list of files that match a particular file mask. If it is found, you can open the
file, as shown in this example
string[] files = userStore.GetFileNames("UserSettings.set");
if (files.Length == 0)
{
Console.WriteLine("File not found");
}
else
{
// ...
}

Categories

Resources