How to Copy URI path file into temp folder? - c#

I have a file path in URI and trying to copy the URI file into C:\temp\ but I am getting an error "Could not find file (from the URI path)" If anyone suggest me would be a great helpful. Thank you.
public String getFile(String uri)
{
// Download file in temp folder
String fileName = Path.GetFileName(uri.Replace("/", "\\"));
Uri fileUri = new Uri(uri);
string fullFilePath = absoluteUri.AbsoluteUri.ToString();
string localPath = new Uri(fullFilePath).LocalPath;
String tempFolder = #"C:\temp\";
File.Copy(localPath, tempFolder);
return fileName;
}

You can use web client to download a file from a Uri
new WebClient().DownloadFile(uri, Path.Combine(filePath, fileName));

I tried in a different way and its working for me. I hope this could help for someone else.
private String getFile(String uri)
{
Uri uriFile = new Uri(uri);
String fileName = Path.GetFileName(uri);
List<String> fileData = new List<String>();
// Reads all the code lines of a file
fileData = readCodeLines(uriFile);
String tempPath = #"c:\temp\";
try
{
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
File.WriteAllLines(tempPath, fileData);
}
catch (IOException ex)
{
MessageBox.Show("Could not find the Temp folder" + " " + tempPath);
}
return fileName;
}

Related

Download Files into a certain path in the internal Storage { C# Xamarin }

currently I am curious how to download files on your android device and save the file to a certain path on the INTERNAL STORAGE. My result I want to get at the end is: If the User click on a button it start to download and replace the file in the path that is defined.
Appreciate any help!
With my current code i tried to modify it directly, but had no success...
Wish y´all a Great Day & thanks for reading!
*Frost
Renegade = new Command(async () =>
{
string pak5 = "";
Stream stream1 = File.OpenRead(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "Android/data/com.epicgames.fortnite/files/InstalledBundles/FortniteBR/FortniteGame/Content/Paks/pakchunk10_s5-Android_ASTCClient.ucas");
/*using (var streamWriter = new StreamWriter(pak5, true))
{
streamWriter.WriteLine(DateTime.UtcNow);
}
using (var streamReader = new StreamReader(pak5))
{
string content = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(content);
}*/
StreamReader reader = new StreamReader(stream1);
string pakspath = reader.ReadToEnd();
//80000000
//80000000
//System.IO.File.Delete("/storage/emulated/0/Android/data/com.epicgames.fortnite/files/InstalledBundles/FortniteBR/FortniteGame/Content/Paks/pakchunk10_s5-Android_ASTCClient.ucas ");
//Utilities.Convert(Body, Body1, pakspath, 80000000);
//Utilities.Convert(Mat, Mat1, pakspath, 8981062);
ReplaceBytes(pakspath, 8981045, S1);
ReplaceBytes(pakspath, 8981045, S2);
ReplaceBytes(pakspath, 80782548, S3);
ReplaceBytes(pakspath, 80782548, S4);
ReplaceBytes(pakspath, 80782571, S5);
ReplaceBytes(pakspath, 80782571, S6);
});
If you are using Xamarin forms then ,Here is my solution.Make a class like this on your
Android project.
public class DroidFileHelper
{
public string GetLocalFilePath(string filename)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
return Path.Combine(path, filename);
}
public async Task SaveFileToDefaultLocation(string fileName, byte[] bytes, bool showFile = false)
{
Context currentContext = Android.App.Application.Context;
string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string file = Path.Combine(directory, fileName);
System.IO.File.WriteAllBytes(file, bytes);
//If you want to open up the file after download the use below code
if (showFile)
{
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.N)
{
string externalStorageState = global::Android.OS.Environment.ExternalStorageState;
var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + global::Android.OS.Environment.DirectoryDownloads + "/" + fileName;
File.WriteAllBytes(externalPath, bytes);
Java.IO.File files = new Java.IO.File(externalPath);
files.SetReadable(true);
string application = "application/pdf";
Intent intent = new Intent(Intent.ActionView);
Android.Net.Uri uri = FileProvider.GetUriForFile(currentContext, "com.companyname.appname.provider", files);
intent.SetDataAndType(uri, application);
intent.SetFlags(ActivityFlags.GrantReadUriPermission);
Forms.Context.StartActivity(intent);
}
else
{
Intent promptInstall = new Intent(Intent.ActionView);
promptInstall.SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(file)), "application/pdf");
promptInstall.SetFlags(ActivityFlags.NewTask);
Forms.Context.StartActivity(promptInstall);
}
}
}
}
after that call it like from your xamarin form.
Xamarin.Forms.DependencyService.Get<IFileHelper>().SaveFileToDefaultLocation(oFile.FileName, oFile.FileInBytes, true);
It will save your file to Downloads because we set the path as Android.OS.Environment.DirectoryDownloads in our droid helper class

Uploading file in ASP.NET to server

I'm working on a website where users could apply to a certain job online.
A user must submit information in addition to a CV.
I'm new to this kind of work I would appreciate any kind of help.
Here is my attempt for the post method, but it generates the following exception:
Unexpected end of stream. Is there an end boundary?
public async Task<IHttpActionResult> PostCV()
{
IList<string> AllowedFileExtensions = new List<string> { ".txt", ".pdf" };
var parser = new MultipartFormDataParser(await Request.Content.ReadAsStreamAsync());
IList<FilePart> files = parser.Files;
IList<ParameterPart> formData = parser.Parameters;
FilePart uploadedContent = files.First();
var originalContentFileName =
uploadedContent.FileName.Trim('\"');
var originalExtension = Path.GetExtension(originalContentFileName);
if (!AllowedFileExtensions.Contains(originalExtension))
return BadRequest("Bad extension");
string modifiedContentFileName =
string.Format("{0}{1}", Guid.NewGuid().ToString(),
originalExtension);
Stream input = uploadedContent.Data;
string Url = string.Empty;
string fileName = string.Empty;
string directoryName = string.Empty;
directoryName = Path.Combine(HttpRuntime.AppDomainAppPath, "Uploads");
fileName = Path.Combine(directoryName, modifiedContentFileName);
if (File.Exists(fileName))
File.Delete(fileName);
using (Stream file = File.OpenWrite(fileName))
{
try
{
input.CopyTo(file);
file.Close();
var cv = new CV{ Path = fileName };
db.CVs.Add(cv);
db.SaveChanges();
return Json(cv);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
Thanks in advance
Apparently I should have chosen form-data in the body section, set the key with anything (e.g filename) and in the value choose file.
Also you need to create a folder in your path, in my case called Uploads in the directory specified.
Lots of thanks for those who helped.

how to compress Input stream using c#?

I have write code for the image upload using c# web api. now i want to image upload done with on server. and this thing is also done.but i want to compress the image then after upload on server. but how can do i have no idea any one know how can do that then please let me know. i want to compress image then upload on amzon s3 server using webapi.
This is my code =>
[HttpPost]
[Route("FileUpload")]
public HttpResponseMessage FileUpload()
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
string fname = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName.ToString());
string extension = Path.GetExtension(postedFile.FileName);
Image img = null;
string newFileName = "";
string path = "";
img = Image.FromStream(postedFile.InputStream);
string path = ConfigurationManager.AppSettings["ImageUploadPath"].ToString();
newFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".jpeg";
string filePath = Path.Combine(path, newFileName);
UploadImageOnServer(postedFile.InputStream,path + newFileName);
}
}
}
catch (Exception ex)
{
}
return Request.CreateResponse(HttpStatusCode.OK, "Done");
}
This is my server on upload code =>
public static void UploadImageOnServer(Stream File, string Key)
{
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = Bucketname,
InputStream = File,
CannedACL = S3CannedACL.PublicRead,
Key = Key
};
PutObjectResponse response = client.PutObject(putRequest);
}
This is my code now i want to compress image. please any one know then please let me know.

Xamarin.Forms Deleting Files at Runtime iOS

I need to store a byte[] in memory. I need to access it later. The byte[] represents a video. The following code will allow the file to be written to memory, as well as accessed from memory. When the remove method shown below is called, it can still be accessed later.
I have checked that the pathname is the same.
public void StoreVideo(byte[] video, string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
Directory.CreateDirectory(directoryname);
var path = Path.Combine(directoryname, filename);
File.WriteAllBytes(path, video);
}
public void RemoveVideo(string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
var path = Path.Combine(directoryname, filename);
File.Delete(filename);
}
public byte[] GetVideo(string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
var path = Path.Combine(directoryname, filename);
if(File.Exists(path))
{
return File.ReadAllBytes(path);
}
return null;
}
The answer to this was just a small brain fart on the path being passed to the File.Delete method. However for those who run into this you should be aware that File.Delete DOES NOT throw any exception if it cannot delete the file. It should be good practice to wrap the File.Delete method a check for File.Exists

Move files from one folder to another C# Error File being used by another process

I tired to copy files containing a particular string from one folder to another but it keeps giving me the error message System.IO.IOException: The process cannot access the file 'Z:\Upload\Text-File-1.txt' because it is being used by another process. Have tried a few things but nothing works. Not sure how to fix it.
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CheckandMoveFiles();
}
private static void CheckandMoveFiles()
{
//put filenames in array
string[] sourcePath = Directory.GetFiles(#"Z:\Upload\");
string targetPath = #"Z:\Upload\TextFiles\";
try
{
//Get each filepath and check for string
foreach (string name in sourcePath)
{
string d = "Text";
if (name.Contains(d))
{
string fileName = name;
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
using (StreamReader reader = new StreamReader(sourceFile))
{
File.Copy(sourceFile, destFile, true);
}
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex); // Write error
}
Console.WriteLine("****************************DONE***************************************");
Console.ReadLine();
}
}
}
It looks like your problem is in the following lines:
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
because fileName already contains the full path, and sourcePath is a string array, so sourcePath.ToString() would not yield the path you expect.
Instead try:
string sourceFile = fileName;
string destFile = System.IO.Path.Combine(targetPath, System.IO.Path.GetFileName(fileName));
using (StreamReader reader = new StreamReader(sourceFile))
{
File.Copy(sourceFile, destFile, true);
}
You're opening a StreamReader to read the sourceFile, and then you try to File.Copy() it? that's why you're getting the error
Lose the StreamReader, you don't need it
File.Copy(sourceFile, destFile, true);
Will do
Should be like this:
if (name.Contains(d))
{
string fileName = name;
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
File.Copy(sourceFile, destFile, true);
}
File.Copy takes file path as parameter not the stream that points to the file.
Try This Friend...
public class SimpleFileCopy
{
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}

Categories

Resources