C# System.UnauthorizedAccessException when using stream - c#

I am trying to upload some files to Google Drive via my C# programme. I am using stream to work with Google Drive API function to upload a file. But I have the exception called System.UnauthorizedAccessException. But when I use File.ReadAllText function I have not got the exception. Here's my code and exception is on line 7. Thank you for your answers.
public void uploadFile(string path, DriveService service)
{
var fileMetadata = new Google.Apis.Drive.v3.Data.File();
fileMetadata.Name = Path.GetFileName(path);
fileMetadata.MimeType = "txt";
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
{
request = service.Files.Create(fileMetadata, stream, "txt");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
}
EDIT 1:
There is link to GitHub to full source code from my project: https://github.com/Nextesro/IDK-client

Use File.OpenRead to open the file for read-only access.
using (var stream = File.OpenRead(path))
{
// ...
}

Related

Uploaded file have no content when uploaded from Remote IIS Server

I am trying to upload files to Google Drive using ASP.NET Core 3.0, here is my code to upload the file.
GData.File fileMetadata = new GData.File()
{
Id = null,
Name = Path.GetFileName(path),
MimeType = contentType
};
using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
FilesResource.CreateMediaUpload request = service.Files.Create(fileMetadata, stream, contentType);
request.Fields = "id";
request.Body = fileMetadata;
request.ProgressChanged += (uploadProgress) =>
{
Debug.WriteLine($"{uploadProgress.Status} {uploadProgress.BytesSent}");
};
request.ResponseReceived += (obj) =>
{
Debug.WriteLine($"File uploaded successfully {obj.Id}");
};
request.Upload();
}
Problem i am facing is, this method work fine when i run it on local IIS Server. On Remote IIS Server this method run successfully but uploaded file do not have any content in it and show 0 size
follow this link to test:
https://oauthdemo.coredata.ca/
I tested the link you provided, but the test results show that the Content-Length has a size.
After struggling of whole day finally i have sort this issue.
It was due to the temp folder. i was using FileStream to create new file in temp folder. It was a A-Sync call due to which FileStream failed to create that file.

web api 2 - excel spreadsheet (the file is corrupt and cannot be opened)

I am trying to download a simple xlsx file using web api but the file is always corrupt and I am yet to figure out why.I am using C# ClosedXML.Excel and following a basic example which can be found here:
ClosedXml examples
[HttpGet]
[Route("campaigns/{id}/contact-points/excel")]
[SwaggerResponse(491, "TokenInvalid")]
[SwaggerResponse(HttpStatusCode.NotFound)]
[SwaggerResponse(HttpStatusCode.Forbidden)]
[ResponseType(typeof(HttpResponseMessage))]
public async Task<IHttpActionResult> GetCampaignContactPointsExcel(int id, int frequency, string txtFrequency)
{
var wb = new XLWorkbook();
var ws1 = wb.Worksheets.Add("Sheet1");
ws1.Cell("A1").SetValue(1).AddToNamed("value1");
var ws2 = wb.Worksheets.Add("Sheet2");
ws2.Cell("A1").SetFormulaA1("=value1").AddToNamed("value2");
var responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
using (var memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
responseMessage.Content = new ByteArrayContent(memoryStream.ToArray());
responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
responseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "ContactPoints.xlsx"
};
memoryStream.Close();
}
return ResponseMessage(responseMessage);
}
I am also using swagger and when I click on the link it downloads the file and opens it as a xlsx file but it always says it's corrupt.
There is nothing wrong in the backend code. On the frontend side you need to set responseType='blob'
Seems like this is an issue related to swagger ui 2. Please refer to [https://github.com/swagger-api/swagger-ui/issues/1605][1].
You can try curl or Postman to see if it downloads the file correctly.
While calling the service set Response type as 'blob'
return this.http.get(this.url +'PA/Downloadexcel/'+revisionId,{ responseType :'blob'});

How to download a file on the client device using Windows.Web.Http

I am working on a Windows to UWP app. A web service exists that when called (GET), returns a file. When the web service is triggered using a browser, it successfully downloads a file on the browser.
On the UWP app, I am using Windows.Web.Http to call the web service. I need to save get the file sent by the web service and save it on the device.
I currently have the following code. Not sure how to get the result from the web service and save to the file.
public async Task DownloadFile(string WebServiceURL, string PathToSave)
{
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
using (IInputStream inputStream = await result.Content.ReadAsInputStreamAsync())
{
//not sure if this is correct and if it is, how to save this to a file
}
}
Using System.Web.Http, I am able to easily do this using the following:
Stream stream = result.Content.ReadAsStreamAsync().Result;
var fileStream = File.Create(PathToSave);
await stream.CopyToAsync(fileStream);
fileStream.Dispose();
stream.Dispose();
However, using Windows.Web.Http, I am not sure how I can do this. Please help!
this what you looking for?
like this?
var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
myFilter.AllowUI = false;
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(myFilter);
Windows.Web.Http.HttpResponseMessage result = await client.GetAsync(new Uri(WebServiceURL));
//not sure if this is correct and if it is, how to save this to a file
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename.tmp", CreationCollisionOption.GenerateUniqueName);
using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await result.Content.WriteToStreamAsync(filestream);
await filestream.FlushAsync();
}

Unable to upload image to Amazon s3 from Windows Phone using .NET SDK for Amazon

I am using .NET SDK for Amazon S3 in my Windows Phone 8 project. I am using the following code,
public async void UploadFile(string bucketName, string filepath)
{
string awsID = "myID";
string secretKey = "mysecretkey";
AmazonS3Client s3Client = new AmazonS3Client(awsID, secretKey);
var request = new PutObjectRequest()
{
BucketName = "bucketname",
InputStream = App.GetResourceStream(new Uri("projectname;component/Assets/call.png", UriKind.Relative)).Stream
};
await s3Client.PutObjectAsync(request);
Console.WriteLine("File Uploaded");
}
I have set the content type of image as "Resource"
I am getting this error
XML is malformed from amazon s3.
On googling i found a links3-put fails to send file asking me to append filename with name of the bucket.On doing so,I know get a folder created inside my bucket int he name of file and my contents are not uploaded.
For WinRT and Windows Phone FilePath property must be in the form of "ms-appdata:///local/file.txt" as mentioned here.
To upload from isolated storage you can use InputStream property.
var request = new PutObjectRequest()
{
BucketName = "bucketname",
InputStream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("YOUR_FILE_PATH", FileMode.Open);
};

URL Formats are not supported

I am reading File with File.OpenRead method, I am giving this path
http://localhost:10001/MyFiles/folder/abc.png
I have tried this as well but no luck
http://localhost:10001//MyFiles//abc.png
but its giving
URL Formats are not supported
When I give physical path of my Drive like this,It works fine
d:\MyFolder\MyProject\MyFiles\folder\abc.png
How can I give file path to an Http path?
this is my code
public FileStream GetFile(string filename)
{
FileStream file = File.OpenRead(filename);
return file;
}
Have a look at WebClient (MSDN docs), it has many utility methods for downloading data from the web.
If you want the resource as a Stream, try:
using(WebClient webClient = new WebClient())
{
using(Stream stream = webClient.OpenRead(uriString))
{
using( StreamReader sr = new StreamReader(stream) )
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
You could either use a WebClient as suggested in other answers or fetch the relative path like this:
var url = "http://localhost:10001/MyFiles/folder/abc.png";
var uri = new Uri(url);
var path = Path.GetFileName(uri.AbsolutePath);
var file = GetFile(path);
// ...
In general you should get rid of the absolute URLs.
The best way to download the HTML is by using the WebClient class. You do this like:
private string GetWebsiteHtml(string url)
{
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
stream.Dispose();
reader.Dispose();
return result;
}
Then, If you want to further process the HTML to ex. extract images or links, you will want to use technique known as HTML scrapping.
It's currently best achieved by using the HTML Agility Pack.
Also, documentation on WebClient class: MSDN
Here I found this snippet. Might do exactly what you need:
using(WebClient client = new WebClient()) {
string s = client.DownloadFile(new Uri("http://.../abc.png"), filename);
}
It uses the WebClient class.
To convert a file:// URL to a UNC file name, you should use the Uri.LocalPath property, as documented.
In other words, you can do this:
public FileStream GetFile(string url)
{
var filename = new Uri(url).LocalPath;
FileStream file = File.OpenRead(filename);
return file;
}

Categories

Resources