Folder acess denied wpf - wpf

I am opening a FileDialog, to let the user select an Audio file, in an MP3 file, and convert it to WAV, the error appears when I am trying to save the file in a new folder that I am creating
var dlg = new OpenFileDialog
{
DefaultExt = ".mp3",
Filter = "Audio files (.mp3)|*.mp3"
};
var res = dlg.ShowDialog();
if (res! == true)
{
var projectPath = Directory.GetParent(Directory.GetCurrentDirectory())?.Parent?.Parent?.FullName;
var FoderName = Path.Combine(projectPath!, "Audios");
Directory.CreateDirectory(FoderName);
using (var mp3 = new Mp3FileReader(dlg.FileName))
{
using (var ws = WaveFormatConversionStream.CreatePcmStream(mp3))
{
WaveFileWriter.CreateWaveFile(FoderName, was) // Error
System.UnauthorizedAccessException: 'Access to the path
'C:\XXX\XXX\XXX\XXX\XXX\XXX' is denied.'
}
}
Thanks

Inside some folders including "Program Files", an app usually has no permission to write a file. Therefore, it is recommended to use a folder dedicated for a specific purpose and made available for apps (you can get path to "Music" by Environment.GetFolderPath(Environment.SpecialFolder.MyMusic).
In general, an app must expect UnauthorizedAccessException when attempting to write a file and prepare a fallback for the case of that exception.

Related

UWP how to get access to file in folder

Help me please, I can't get access to file which I choose by FileOpenPicker.
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
openPicker.CommitButtonText = "Открыть";
openPicker.FileTypeFilter.Add(".xlsx");
var file = await openPicker.PickSingleFileAsync();
using (FileStream fs = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
}
What is wrong?
Because of how UWP sandboxes access to the filesystem, you can't construct a FileStream directly from a StorageFile's path. Instead, you have a few options, in order from simplest to most complex:
1) If your file is small enough, you can just use the helpers in the FileIO static class to read it all at once:
string text = await FileIO.ReadTextAsync(file); // or ReadLinesAsync or ReadBufferAsync, depending on what you need
2) Use the OpenAsync() method on StorageFile:
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read, StorageOpenOptions.AllowReadersAndWriters))
{
// your reading code here
}
If you need to, you can convert between IRandomAccessStream and .NET Streams with the AsStream(), AsStreamForRead() and AsStreamForWrite() extension methods on IRandomAccessStream, the docs for which are here.
3) If you want complete control, you can get a SafeFileHandle to the underlying file using CreateSafeFileHandle(), like so:
SafeFileHandle fileHandle = file.CreateSafeFileHandle(FileAccess.Read, FileShare.ReadWrite);
You can then use this file handle to create a standard FileStream:
using (FileStream fs = new FileStream(fileHandle, FileAccess.Read))
{
// Read stuff here
}
This is the only way to reliably use a FileStream on a UWP StorageFile, and should be used with some caution. The official docs have more details on the implications of doing this.
FileOpenPicker gives you a StorageFile which wraps the opened files and gives you permission to it. This doesn't give you access to the file in general - e.g. you cannot use its Path only to open it with a FileStream. Instead, you need to use the respective Windows.Storage APIs to do this. I usually use the OpenStreamForReadAsync extension method. Add using System.IO to the file header and then:
var stream = await file.OpenStreamForReadAsync();
This method returns a System.IO.Stream which you can use with classic System.IO-enabled APIs.
Please avoid use file Path to access file stream in UWP platform, if you have get the file with FileOpenPicker. You could get the file stream with following.
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
openPicker.CommitButtonText = "Открыть";
openPicker.FileTypeFilter.Add(".xlsx");
var file = await openPicker.PickSingleFileAsync();
if (file != null)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
}
And if you need use stream in System.IO namespace. please call AsStream method for IRandomAccessStream object.
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
System.IO.Stream iostream = stream.AsStream();
For more detail please refer this official document.

file access universal windows filepicker

Im using the FileOpenPicker to let the User choose a file (sqlite-db), which can be anywhere on the computer:
public async Task<string> PickDb()
{
Windows.Storage.StorageFile file = null;
var picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".sqlite");
file = await picker.PickSingleFileAsync();
if (file != null)
return file.Path;
else
return string.empty;
}
This filename is then passed over to sqlite to open a sqlite-connection.
So if the sqlite-file is in the apps home directory, the sqlite-connection is properly opened. If the file is somewhere else, the sqlite-connection gives an read-error.
I know, that UWP-Apps have limited acces to the the filesystem. but as far as I understood, a file returned by a FileOpenPicker, which was manually picked by the user, has always read-write rights.
Where am I wrong?

Can't read file without additional prefix on Intellij

I have met some strange trouble with reading file at Intellij Idea and on Windows 8.1.
And always I got FileNotFoundException.
Here is code snippet:
public XlsReader(String fileName, String sheetName) {
open(fileName, sheetName);
}
public void open(String fileName, String sheetName) {
InputStream fis = null;
try {
if (sheetName == null || sheetName.isEmpty()) {
throw new IllegalArgumentException("Please, provide sheet name");
}
Logger.logDebug("PATH: " + new File(".").getAbsolutePath());
fis = new FileInputStream(fileName);
String resourceFilePath = this.getClass().getResource(fileName).getFile();
Logger.logDebug(resourceFilePath);
fis = new FileInputStream(resourceFilePath);
XSSFWorkbook workBook = new XSSFWorkbook(fis);
sheet = workBook.getSheet(sheetName);
getMetaData();
I couldn't understand why at this line:
new FileInputStream(fileName)
I have got this exception.
And when chcenging path from:
xls = new XlsReader("InputDataIndirect.xlsx", "Calculator");
to:
xls = new XlsReader("test/InputDataIndirect.xlsx", "Calculator");
And it works now.
Here is project struckture:
I tried to load file from class path as well this.getClass().getResource(fileName).getFile() but it wasn't successful.
Any suggestions?
If you're running a main method or test from inside IntelliJ idea, it uses the root of the project as the root to load files from. Therefore, it will look under new_automation, so you need to add the test folder to your path.
To change this, you can change the working directory location in your run configuration to the location you want it to look in for files.

Accessing the images folder in wpf app

I have a wpf application in which I want to save a file in the Images folder, which is on the same level with the bin folder.
How do I access that folder?
I try like this:
using (var imageFile = new FileStream((new Uri(#"pack://application:,,,/Images/Application/")).ToString(), FileMode.Create))
{
//
}
and I get the error that "The given path's format is not supported.". How can I access that folder?
Your path refers to resources within the project assembly. You should use relative or absolute file system paths:
var path = Path.Combine(
Path.DirectorySeparatorChar.ToString(),
AppDomain.CurrentDomain.BaseDirectory,
"Images"); // Result could be for example: "C:\MyWorkspace\MyProject\bin\Debug\Images"
using (var imageFile = new FileStream(path, FileMode.Create)) { }
How about using double dots(..) to get to parent directory.
using (var imageFile = new FileStream("..\..\[Path goes here]", FileMode.Create))
{
//
}

Sharepoint 2010 Upload file using Silverlight 4.0

I am trying to do a file upload from Silverlight(Client Object Model) to Sharepoint 2010 library.. Please see the code below..
try{
context = new ClientContext("http://deepu-pc/");
web = context.Web;
context.Load(web);
OpenFileDialog oFileDialog = new OpenFileDialog();
oFileDialog.FilterIndex = 1;
oFileDialog.Multiselect = false;
if (oFileDialog.ShowDialog().Value == true)
{
var localFile = new FileCreationInformation();
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
localFile.Url = System.IO.Path.GetFileName(oFileDialog.File.Name);
List docs = web.Lists.GetByTitle("Gallery");
context.Load(docs);
File file = docs.RootFolder.Files.Add(localFile);
context.Load(file);
context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
}
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
But I am getting the following error
System.Security.SecurityException: File operation not permitted. Access to path '' is denied.
at System.IO.FileSecurityState.EnsureState()
at System.IO.FileSystemInfo.get_FullName()
at ImageUploadSilverlight.MainPage.FileUpload_Click(Object sender, RoutedEventArgs e)
Any help would be appreciated
Thanks
Deepu
Silverlight runs with very restricted access to the client user's filesystem. When using an open-file dialog, you can get the name of the selected file within its parent folder, the length of the file, and a stream from which to read the data in the file, but not much more than that. You can't read the full path of the file selected, and you are getting the exception because you are attempting to do precisely that.
If you want to read the entire content of the file into a byte array, you'll have to replace the line
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
with something like
localFile.content = ReadFully(oFileDialog.File.OpenRead());
The ReadFully method reads the entire content of a stream into a byte array. It's not a standard Silverlight method; instead it
is taken from this answer. (I gave this method a quick test on Silverlight, and it appears to work.)

Resources