Read file right after it was created and closed [duplicate] - c#

This question already has answers here:
File being used by another process after using File.Create()
(11 answers)
Closed 1 year ago.
After creating a file via File.Create, I want to read it afterwards with File.ReadAllText. However, I always get an exception that says that the process cannot access the file. Once the file is created, access works without problems.
So I assume that the file is not yet released by File.Create at the time where it should be read. How do I solve this? Below is my method.
public SettingsModel LoadSettings()
{
var _fullPath = FileHelper.GetFullPath(_fileName);
if (!File.Exists(_fullPath))
{
File.Create(_fullPath).Close();
}
var serializedSettings = File.ReadAllText(_fullPath);
var settings = JsonConvert.DeserializeObject<SettingsModel>(serializedSettings);
if (settings == null)
{
return new SettingsModel();
}
else
{
return settings;
}
}

You create an empty file to deserialize it afterwards. You can perform deserialization only if the file exists:
public SettingsModel LoadSettings()
{
var _fullPath = FileHelper.GetFullPath(_fileName);
var settings = File.Exists(_fullPath)
? JsonConvert.DeserializeObject<SettingsModel>(File.ReadAllText(_fullPath))
: new SettingsModel();
return settings;
}

Related

Cannot load nlog.config in Xamarin

I cannot read nlog.config file in asset folder of android platform
NLog.LogManager.Configuration = new XmlLoggingConfiguration("NLog.config");
How to read nlog file and also this file is in android asset.
You can also make use of Xamarin resource. Put the NLog.config file into the library project, then edit file's properties - change the build action to embedded resource.
public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName)
{
var resourcePaths = assembly.GetManifestResourceNames()
.Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase))
.ToList();
if (resourcePaths.Count == 1)
{
return assembly.GetManifestResourceStream(resourcePaths.Single());
}
return null;
}
var nlogConfigFile = GetEmbeddedResourceStream(myAssembly, "NLog.config");
if (nlogConfigFile != null)
{
var xmlReader = System.Xml.XmlReader.Create(nlogConfigFile);
NLog.LogManager.Configuration = new XmlLoggingConfiguration(xmlReader, null);
}
See also: https://github.com/NLog/NLog/wiki/Explicit-NLog-configuration-loading#loading-nlog-configuration-from-xamarin-resource
you could also try to use this (nlog.config file with a Build Action as an AndroidAsset):
NLog.LogManager.Configuration = new XmlLoggingConfiguration (XmlTextReader.Create(Assets.Open ("NLog.config")), null);
refer to:
https://github.com/NLog/NLog/blob/master/src/NLog/Config/LoggingConfigurationFileLoader.cs#L101-L120
You can add an extension method to your context class that gets you the required asset as a stream:
public static class Utils
{
public static Stream GetFromAssets(this Context context, string assetName)
{
AssetManager assetManager = context.Assets;
Stream inputStream;
try
{
using (inputStream = assetManager.Open(assetName))
{
return inputStream;
}
}
catch (Exception e)
{
return null;
}
}
}
And then in your activity context access it like:
var Asset= context.GetFromAssets("AssetName");
Note that this will return a System.IO.Stream.
Good luck
Revert in case of queries.
For Xamarin Android "NLog.config" (in this casing) in the assets folder will be loaded automatically. If the file name is different, then use:
LogManager.Configuration = new XmlLoggingConfiguration("assets/someothername.config");
Thanks for your response. I resolved this issue by setting autoReload="false" throwExceptions="false". Due to these two my config file was not visible. I dont know how they affect the file visibility but setting above two to false i can get config file now
Thanks,

UWP Check If File Exists

I am currently working on a Windows 10 UWP App.
The App needs to Check if a certain PDF File exists called "01-introduction", and if so open it.
I already have the code for if the file does not exist.
The Code Below is what i currently have:
try
{
var test = await DownloadsFolder.CreateFileAsync("01-Introduction.pdf", CreationCollisionOption.FailIfExists);
}
catch
{
}
This code Does not work correctly because to check if the file exists here, I attempt to create the file. However if the file does not already exist an empty file will be created. I do not want to create anything if the file does not exist, just open the PDF if it does.
If possible, i would like to look inside a folder which is in the downloads folder called "My Manuals".
Any help would be greatly appreciated.
public async Task<bool> IsFilePresent(string fileName)
{
var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName);
return item != null;
}
But not support Win8/WP8.1
https://blogs.msdn.microsoft.com/shashankyerramilli/2014/02/17/check-if-a-file-exists-in-windows-phone-8-and-winrt-without-exception/
There are two methods
1) You can use StorageFolder.GetFileAsync() as this is also supported by Windows 8.1 and WP 8.1 devices.
try
{
StorageFile file = await DownloadsFolder.GetFileAsync("01-Introduction.pdf");
}
catch
{
Debug.WriteLine("File does not exits");
}
2) Or you can use FileInfo.Exists only supported for windows 10 UWP.
FileInfo fInfo = new FileInfo("01-Introduction.pdf");
if (!fInfo.Exists)
{
Debug.WriteLine("File does not exits");
}
System.IO.File.Exists is UWP way too. I test now in Windows IOT. it just works.
This helped me in my case:
ApplicationData.Current.LocalFolder.GetFileAsync(path).AsTask().ContinueWith(item => {
if (item.IsFaulted)
return; // file not found
else { /* process file here */ }
});
This worked for me running my UWP C# app on Windows 10...
StorageFolder app_StorageFolder = await StorageFolder.GetFolderFromPathAsync( #App.STORAGE_FOLDER_PATH );
var item = await app_StorageFolder.TryGetItemAsync(relative_file_pathname);
return item != null;
public override bool Exists(string filePath)
{
try
{
string path = Path.GetDirectoryName(filePath);
var fileName = Path.GetFileName(filePath);
StorageFolder accessFolder = StorageFolder.GetFolderFromPathAsync(path).AsTask().GetAwaiter().GetResult();
StorageFile file = accessFolder.GetFileAsync(fileName).AsTask().GetAwaiter().GetResult();
return file != null;
}
catch
{
return false;
}
}
You can use System.IO.File.
Example:
// If file located in local folder. You can do the same for other locations.
string rootPath = ApplicationData.Current.LocalFolder.Path;
string filePath = Path.Combine(rootPath, "fileName.pdf");
if (System.IO.File.Exists(filePath))
{
// File exists
}
else
{
// File doesn't exist
}
I'm doing a Win10 IoT Core UWP app and I have to check the file length instead of "Exists" because CreateFileAsync() already creates an empty file stub immediately. But I need that call before to determine the whole path the file will be located at.
So it's:
var destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("MyFile.wow", ...);
if (new FileInfo(destinationFile.Path).Length > 0)
return destinationFile.Path;
In this way System.IO.File.Exists(filePath) I cannot test DocumentLibrary
because KnownFolders.DocumentsLibrary.Path return empty string
Next solution is very slow await DownloadsFolder.GetFileAsync("01-Introduction.pdf")
IMHO the best way is collect all files from folder and check the file name exist.
List<StorageFile> storageFileList = new List<StorageFile>();
storageFileList.AddRange(await KnownFolders.DocumentsLibrary.GetFilesAsync(CommonFileQuery.OrderByName));
bool fileExist = storageFileList.Any(x => x.Name == "01-Introduction.pdf");
CreateFileSync exposes an overload that let's you choose what to do if an existing file with the same name has been found in the directory, as such:
StorageFile localDbFile = await DownloadsFolder.CreateFileAsync(LocalDbName, CreationCollisionOption.OpenIfExists);
CreationCollisionOption is the object that you need to set up. In my example i'm opening the file instead of creating a new one.
Based on another answer here, I like
public static async Task<bool> DoesFileExist(string filePath) {
var directoryPath = System.IO.Path.GetDirectoryName(filePath);
var fileName = System.IO.Path.GetFileName(filePath);
var folder = await StorageFolder.GetFolderFromPathAsync(directoryPath);
var file = await folder.TryGetItemAsync(fileName);
return file != null;
}
You can use the FileInfo class in this case. It has a method called FileInfo.Exists() which returns a bool result
https://msdn.microsoft.com/en-us/library/system.io.fileinfo.exists(v=vs.110).aspx
EDIT:
If you want to check for the files existence, you will need to create a StorageFile object and call one of the GetFile.... methods. Such as:
StorageFile file = new StorageFile();
file.GetFileFromPathAsync("Insert path")
if(file == null)
{
/// File doesn't exist
}
I had a quick look to find the download folder path but no joy, but the GetFile method should give you the answer your looking for
On Window 10, for me, this is the most "elegant" way:
private static bool IsFileExistent(StorageFile file)
{
return File.Exists(Path.Combine(file.Path));
}
Or, as an extension if you prefer and will use it widely:
static class Extensions
{
public static bool Exists(this StorageFile file)
{
return File.Exists(Path.Combine(file.Path));
}
}

Redirect subprogram output to a file [duplicate]

This question already has answers here:
redirecting output to the text file c#
(3 answers)
Closed 7 years ago.
I have an answer set program (verified to work) which I would like to run within a C# console application. I want to redirect the output of that program to a text file which I can then read from later on. I tried:
string directory = #"C:\...\Clingo";
string clingoPath = "clingo.exe";
string inputPath = "Assignment2.lp";
string dataPath = "Data1.lp";
string outputPath = "result.txt";
string arguments = String.Format("1 \"{0}\" \"{1}\" >\"{2}\"", inputPath, dataPath, outputPath);
// Set the necessary properties for the process
ProcessStartInfo clingoProcessInfo = new ProcessStartInfo(clingoPath, arguments);
clingoProcessInfo.WorkingDirectory = directory;
clingoProcessInfo.UseShellExecute = false;
// Start the process
Process clingoProcess = Process.Start(clingoProcessInfo);
However, when run, I get the following error:
"***ERROR: (clingo): '>result.txt': could not open input file!"
I would like to know how to fix that.
using System.IO;
if (!File.Exists(outputPath))
{
FileStream fs = new FileStream(outputPath, FileMode.CreateNew);
}
//now do the rest of your stuff

How to check if a file exist in windowsstore app [duplicate]

This question already has answers here:
How to check if file exists in a Windows Store App?
(10 answers)
Closed 9 years ago.
While making a lab on window 8 app dev. I could not load all images needed. So inorder for the share part to work with a sharing imag I need to check if the image file is availeble.
The project is a windows grid app using XAML and C#
In the past I used
Using System.IO
... lost of code
privat void share()
....
if (File.exist(filename)
{
add file to share
}
If i try this in my window8 project. The File class is not found.
I search the internet but could not find a code example that checkes the existance in a windowsstore app in C#
Michiel
you need StorageFile not File
here is simple example to check and get the file
StorageFile file;
try {
file = await ApplicationData.Current.LocalFolder.GetFileAsync("foo.txt");
}
catch (FileNotFoundException) {
file = null;
}
you can write a function
public static async Task<bool> FileExistsAsync(this StorageFolder folder, string fileName)
{
try
{
await folder.GetFileAsync(fileName);
return true;
}
catch (FileNotFoundException)
{
return false;
}
}
If you know the path in your local storage and you have a bunch of files to check, you can do the following...
var sourceFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
sourceFolder = await sourceFolder.GetFolderAsync("Assets");
var files = await sourceFolder.GetFilesAsync();
var requiredFiles = new List<String> { "ThisWorks.png", "NotHere.png" };
foreach(var filename in requiredFiles)
{
// your example logic here...
Debug.WriteLine(filename + " " + (files.Any(f => f.Name == filename) ? "Exists" : "Doesn't exist"));
}

Custom Checkin Policy: Access to filecontent from changeset files

I'm trying to write my own checking policy.
I want to review if any .cs file contains some code. So my question is, if its possible to get the content of every file from the changeset in the overridden Initialize-Method and/or Evaluate-Method (from PolicyBase).
You can't get the contents from the files directly, you'll need to open them yourselves. For each checked In your Evaluate method, you should look at the PendingCheckin.PendingChanges.CheckedPendingChanges (to ensure that you only limit yourself to the pending changes that will be checked in.) Each PendingChange has a LocalItem that you can open and scan.
For example:
public override PolicyFailure[] Evaluate()
{
List<PolicyFailure> failures = new List<PolicyFailure>();
foreach(PendingChange pc in PendingCheckin.PendingChanges.CheckedPendingChanges)
{
if(pc.LocalItem == null)
{
continue;
}
/* Open the file */
using(FileStream fs = new FileStream(pc.LocalItem, ...))
{
if(/* File contains your prohibited code */)
{
failures.Add(new PolicyFailure(/* Explain the problem */));
}
fs.Close();
}
}
return failures.ToArray();
}

Categories