Code can create the directory but throws the exception `UnauthorizedAccessException` while copying the file to a directory - asp.net-core

I am getting UnauthorizedAccessException while copying the file to a directory, inside the wwwroot. However Directory.CreateDirectory(uploadFolderPath); creates the folder.
The code I am using to create the folder and copy the files is shown below.
public string UploadPdfFile(IFormFile file, string folderName)
{
if (file == null || file.Length == 0)
{
return string.Empty;
}
// Define the file path
string uploadFolderPath = Path.Combine(_env.WebRootPath, #"uploads\books", $"{folderName}");
if (!Directory.Exists(uploadFolderPath))
Directory.CreateDirectory(uploadFolderPath);
// Save the file to the drive
using (var stream = new FileStream(uploadFolderPath, FileMode.Create))
{
file.CopyTo(stream);
}
return uploadFolderPath;
}
The error says:
UnauthorizedAccessException: Access to the path 'D:\Project\XX-Pedia\XX-Pedia\wwwroot\Uploads\Books\c1' is denied.
What is the solution for this?
I am running the visual studio in administrative mode.
This is strange because the code can create the folder but couldn't copy the files to the folder.

Turns out that I was missing the actual filename component...
string uploadFolderPath = Path.Combine(_env.WebRootPath, #"uploads\books", $"{folderName}");
if (!Directory.Exists(uploadFolderPath))
Directory.CreateDirectory(uploadFolderPath);
//added this line
string filepath = Path.Combine(uploadFolderPath, file.FileName);
// Save the file to the drive
using (var stream = new FileStream(filepath, FileMode.Create))
{
file.CopyTo(stream);
}

Related

non-invocable member 'File' cannot be used like a method error message- what am I missing?

I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?
This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.

Xamarin Android: How to Share PDF File From Assets Folder? Via WhatsApp I get message that the file you picked was not a document

I use Xamarin Android. I have a PDF File stored in Assets folder from Xamarin Android.
I want to share this file in WhatsApp, but I receive the message:
The file you picked was not a document.
I tried two ways:
This is the first way
var SendButton = FindViewById<Button>(Resource.Id.SendButton);
SendButton.Click += (s, e) =>
{
////Create a new file in the exteranl storage and copy the file from assets folder to external storage folder
Java.IO.File dstFile = new Java.IO.File(Environment.ExternalStorageDirectory.Path + "/my-pdf-File--2017.pdf");
dstFile.CreateNewFile();
var inputStream = new FileInputStream(Assets.OpenFd("my-pdf-File--2017.pdf").FileDescriptor);
var outputStream = new FileOutputStream(dstFile);
CopyFile(inputStream, outputStream);
//to let system scan the audio file and detect it
Intent intent = new Intent(Intent.ActionMediaScannerScanFile);
intent.SetData(Uri.FromFile(dstFile));
this.SendBroadcast(intent);
//share the Uri of the file
var sharingIntent = new Intent();
sharingIntent.SetAction(Intent.ActionSend);
sharingIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(dstFile));
sharingIntent.SetType("application/pdf");
this.StartActivity(Intent.CreateChooser(sharingIntent, "#string/QuotationShare"));
};
This is the second
//Other way
var SendButton2 = FindViewById<Button>(Resource.Id.SendButton2);
SendButton2.Click += (s, e) =>
{
Intent intent = new Intent(Intent.ActionSend);
intent.SetType("application/pdf");
Uri uri = Uri.Parse(Environment.ExternalStorageDirectory.Path + "/my-pdf-File--2017.pdf");
intent.PutExtra(Intent.ExtraStream, uri);
try
{
StartActivity(Intent.CreateChooser(intent, "Share PDF file"));
}
catch (System.Exception ex)
{
Toast.MakeText(this, "Error: Cannot open or share created PDF report. " + ex.Message, ToastLength.Short).Show();
}
};
In other way, when I share via email, the PDF file is sent empty (corrupt file)
What can I do?
The solution is copying de .pdf file from assets folder to a local storage. Then We able to share de file.
First copy the file:
string fileName = "my-pdf-File--2017.pdf";
var localFolder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var MyFilePath = System.IO.Path.Combine(localFolder, fileName);
using (var streamReader = new StreamReader(Assets.Open(fileName)))
{
using (var memstream = new MemoryStream())
{
streamReader.BaseStream.CopyTo(memstream);
var bytes = memstream.ToArray();
//write to local storage
System.IO.File.WriteAllBytes(MyFilePath, bytes);
MyFilePath = $"file://{localFolder}/{fileName}";
}
}
Then share the file, from local storage:
var fileUri = Android.Net.Uri.Parse(MyFilePath);
var intent = new Intent();
intent.SetFlags(ActivityFlags.ClearTop);
intent.SetFlags(ActivityFlags.NewTask);
intent.SetAction(Intent.ActionSend);
intent.SetType("*/*");
intent.PutExtra(Intent.ExtraStream, fileUri);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
var chooserIntent = Intent.CreateChooser(intent, title);
chooserIntent.SetFlags(ActivityFlags.ClearTop);
chooserIntent.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(chooserIntent);
the file you picked was not a document
I had this issue when I trying to share a .pdf file via WhatsApp from assets folder, but it gives me the same error as your question :
the file you picked was not a document
Finally I got a solution that copy the .pdf file in assets folder to Download folder, it works fine :
var pathFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
Java.IO.File dstFile = new Java.IO.File(pathFile.AbsolutePath + "/my-pdf-File--2017.pdf");
Effect like this.

how to get a directory path as an input and read a file from that path in java?

i want to read files by a directory path string,
for example i want this method to return the corresponding file:
File reader(String pathFile){....
return File;}
File reader(String pathFile){
return File;}
in the reader function :
File f = new File(directoryPath,filename);
f.createNewFile(); //to create a new file in the directory.surround with try and catch as it throws IOEXCEPTION
return f;
you can also use f.mkdir() to create new directory if it doesnt exist.

Upload file with meta data and checkin to sharpoint folder using Client Object Model

Hi I'm trying to upload a file to sharepoint 2010 using the client api with meta data and also checkin the file after I'm done. Below is my code:
public void UploadDocument(SharePointFolder folder, String filename, Boolean overwrite)
{
var fileInfo = new FileInfo(filename);
var targetLocation = String.Format("{0}{1}{2}", folder.ServerRelativeUrl,
Path.AltDirectorySeparatorChar, fileInfo.Name);
using (var fs = new FileStream(filename, FileMode.Open))
{
SPFile.SaveBinaryDirect(mClientContext, targetLocation, fs, overwrite);
}
// doesn't work
SPFile newFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();
//check out to make sure not to create multiple versions
newFile.CheckOut();
// use OverwriteCheckIn type to make sure not to create multiple versions
newFile.CheckIn("test", CheckinType.OverwriteCheckIn);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();
//SPFile uploadFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
//uploadFile.CheckOut();
//uploadFile.CheckIn("SOME VERSION COMMENT I'D LIKE TO ADD", CheckinType.OverwriteCheckIn);
//mClientContext.ExecuteQuery();
}
I'm able to upload the file but I can't add any meta data and file is checked out. I want to add some meta data and checkin the file after I'm done.
My SharePointFolder class has the serverRelativeUrl of the folder path to upload to. Any help greatly appreciated.
You need a credential before the executeQuery(); and SaveBinaryDirect();
For example:
mClientContext.Credentials = new NetworkCredential("LoginID","LoginPW", "LoginDomain");
SPFile newFile = mRootWeb.GetFileByServerRelativeUrl(targetLocation);
mClientContext.Load(newFile);
mClientContext.ExecuteQuery();

Cannot read a file when running program from commandline, but it works from Eclipse

I have a simple java program that runs fine in eclipse but cannot find the .txt files I read from and write to when run from command line. I tried changing the permissions of the files but because they run in eclipse it seems that is not the issue. I'm not experienced in reading from files in Java. But I think it is a path issue or something. Can anyone help me fix my script or whatever so it works?
I get a bunch of these:
java.io.FileNotFoundException: helloState.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at bot.FileRead.readByLine(FileRead.java:33)
at bot.BuildStates.buildStates(BuildStates.java:16)
at bot.Kate.main(Kate.java:98)
My file structure is as follows CS317_A4/src/myPackage/(class and source files)
My text files are in the CS317_A4 directory and my script is in the src directory (I can't seem to run the program from the CS317_A4 directory
Here is my script for running the program:
#!/bin/bash
set classpath=
java -cp .:.. bot.Kate
Here is how I open the file:
public LinkedList<String> readByLine(String filename) {
File file = new File(filename);
FileInputStream fis = null;
BufferedInputStream bis = null;
BufferedReader br = null;
String in;
LinkedList<String> fileLines = new LinkedList<String>();
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
br = new BufferedReader(new FileReader(file));
while(br.ready()){
/* read the line from the text file */
in = br.readLine();
/* if the line is empty stop reading */
if(in.isEmpty()){
break;
}
/* add the line to the linked list */
fileLines.add(in);
}
/* dispose all the resources after using them. */
fis.close();
bis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileLines;
}
Try to start it from the directory that's above src. As classpath, use src.