Consider the following code:
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string file = Path.Combine(folder, "test.txt");
File.WriteAllText(file, "test");
string content = File.ReadAllText(file);
Running this on my phone I confirmed that the string content has the value "test", so the file has definitely been created and written to in internal storage.
Next I commented the WriteAllText-line and verified on a second run of the program that the file was still there because the value of content again was "test".
But when I look into the folder returned by GetFolderPath using the file manager of my phone, it is empty. There is no file test.txt.
So the question is, why can't I see the file?
Unless the phone is rooted and the file manager as root permissions you cannot see those files (usually under /data/data/package.name/files)
If you want to see them using your code, consider using this:
String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
Your app should log them with no problem.
If the files are needed outside the app, consider using external storage.
Related
I am trying to download a List of files (user has the option to select multiple). My current code below works fine in localhost (writing and opening the downloads folder). However, when I upload to IIS it gives an error saying that the system configuration is not found.
Please see below:
if (SelectDownloadFiles.Count > 0)
{
//Downloads folder (User profile)
string DownloadFolder = Environment.ExpandEnvironmentVariables("%userprofile%/downloads/");
//This is a little hack to get the literal path for the Downloads folder without too much of back-and-forth and ellaboration
string FolderForward = DownloadFolder.Replace(#"/", #"\");
string Folder = FolderForward.Replace(#"\\", #"\");
foreach (var items in SelectDownloadFiles)
{
//Get Date
var GetDate = items.Substring(0, 6);
//Add 2 days to be consistent to what is displayed to the user (when files were generated)
var FileDate = DateTime.ParseExact(GetDate, "yyMMdd", CultureInfo.InvariantCulture).AddDays(2);
//Get Files
string Pathname = #"D:\";
string FullPathName = Path.Combine(Pathname, items);
byte[] FileBytes = System.IO.File.ReadAllBytes(FullPathName);
MemoryStream Ms = new MemoryStream(FileBytes);
//Rename the file to become user friendly
string DownloadPath = Path.Combine(DownloadFolder, "My Files " + FileDate.ToString("MM-dd-yyyy") + ".zip");
//Write file(s) to folder
FileStream File = new FileStream(DownloadPath, FileMode.Create, FileAccess.Write);
Ms.WriteTo(File);
File.Close();
Ms.Close();
}
//Open Downloads Folder with files
Process.Start("explorer.exe", Folder);
navigationManager.NavigateTo("/default", true);
//DisplayMessage.Show("File(s) successfully downloaded. Please check your “Downloads” folder to access your file(s).", "OK", "check");
}
else
{
Toaster.Add("Please select at least one file to download.", MatToastType.Warning);
}
I've also tried to use the solution below to no avail:
private readonly IWebHostEnvironment _webHostEnvironment;
public YourController (IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment= webHostEnvironment;
}
If I use the "folderoptionpath" and choose "MyDocuments" for instance, the files download to the root path of the files inside IIS.
Is there anything else I need to be doing to get to this to work?
Thanks in advance!
Well, after spending some time researching this, I was finally able to get it going. I ended up using a Nuget Package called BlazorFileSaver and it works just fine. Here's the repo: https://github.com/IvanJosipovic/BlazorFileSaver/blob/master/src/BlazorFileSaver.Sample/Pages/Index.razor
I hope this can help someone else in the future.
What is wrong with this code? The text file is not created in the bin\Debug directory!
string path = Environment.CurrentDirectory + "/" + "Contacts.txt";
if (!File.Exists(path))
{
File.CreateText(path);
MessageBox.Show("file created successfully");
}
using (StreamWriter sw = new StreamWriter("path", true))
{
sw.WriteLine(txtCntname1.Text + "," + txtCntnum1.Text + "," + txtCntnum2.Text + "," + txtCntnum3.Text + ",");
sw.Close();
}
You have two ways of calculating EXE's directory:
1) Implicit
You can use only the file name. In this case, the file will be created in the same folder with EXE file:
File.CreateText("Contacts.txt")
2) Explicit
If you need reliable way to get the EXE's directory, then you need to use AppDomain:
string exe_dir = AppDomain.CurrentDomain.BaseDirectory;
Then, instead of manually concatenating strings to form a path, use Path.Combine method:
string file_path = Path.Combine(exe_dir, "Contact.txt");
The code (Assembly.GetExecutingAssembly().Location), offered by #TobiasTengler, won't work, for instance, for Excel/Word add-in.
Aside from that path should probably not be in quotes here:
using (StreamWriter sw = new StreamWriter("path", true))
Do not use Environment.CurrentDirectory! It does not always represent the directory you started your executable from, since it only represents your working directory.
Please use Assembly.GetExecutingAssembly().Location to get the full path of the executing assembly and then extract only the directory from it, using:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Alternatively you could also use AppDomain.CurrentDomain.BaseDirectory for identifying the directory your application is residing in.
Of course not using an absolute path is a possibility as well, you can create your file using a relative path, by not specifying any directory:
File.CreateText("Contacts.txt")
EDIT:
Seeing how you formed your path, please also use Path.Combine to build your paths:
var appBaseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var contactsFilePath = Path.Combine(appBaseDir, "Contacts.txt");
I am working on an asp.net project using c# and I need to copy a file from an arbitrary location which is determined by the file upload dialog box.
I need to make an exact copy of the file in a folder that is located in the Solutions Explorer. Below is the code I am using.
string filename = txt_lesson_title.text;
string sourcepath = _Uploadedfile.PostedFile.FileName.ToString();
string targetPath = HttpContext.Current.Server.MapPath("/destFolder/");
File.Copy(sourcePath, targetPath + fileName);
The above code runs without reporting any errors but I cannot see the copied files in the destination folder. Any help will be deeply appreciated.
Thanks
You don't need to copy the file, you need to save a copy of it.
You can do this
if the file is coming to your controller, you controller should have arguments like HttpPostedFileBase or HttpPostedFileBase[] depending on if you are saving one or more
if you are saving one,
public ActionResult Step(FormCollection collection, HttpPostedFileBase file) {
//HttpPostedFileBase file; //this comes from you controller argument
var directory = "~/Uploads/";
//this if statement can be optional
if(!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(directory)))
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(directory));
var virtualPath = directory + "/" + <your file name here>;
var filePath = System.Web.HttpContext.Current.Server.MapPath(virtualPath);
//if the file exists already, delete and replace it with the new one
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
file.SaveAs(filePath);
}
else {
//do as above without the create directory
}
}
I want to download a folder with its files in various mime type. My virtual path is "http://localhost/attachments/". My sub folders are "certificates/id". So when clicking on a grid i pass id to the download page. But it throws an exception like virtual path is invalid. 'http://localhost/attachments/certificates/id)'.
In below code, Request.Params[0] meant id, this points the endlevel folder which i want to make a zip folder.
Any guidance would be grateful.
using (ZipFile zip = new ZipFile())
{
string VirtualPath = ConfigurationManager.AppSettings.Get("AttachmentsShowVirtualPath");
string Path = string.Empty;
Path = "certificates" + "/";
string folderPath = VirtualPath + Path + Request.Params[0] + "/";
zip.CompressionLevel = CompressionLevel.None;
zip.AddSelectedFiles(".", Server.MapPath(folderPath), "", false);
zip.Save(Response.OutputStream);
}
First, are you using DotNetZip? I have never use it, but try changing the . to *.*
If not getting the file, try to do Directory.GetFiles to check if eveything is pointing correctly and your code has read permission over the directory https://msdn.microsoft.com/en-us/library/07wt70x2%28v=vs.110%29.aspx
Or try to use official Zip class from https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx With this method: ZipFile.CreateFromDirectory
I am trying to copy a file (.docx, .pdf, .pptx etc) from a source folder(on server) to a destination folder(on client).
The user can choose which among the list of files that he wants to download. He selects the files and then downloads it(Copies it to his computer) to the destination path
dstnLocation= #"C:\Fldr\Docs;
My Code:
string sourceLocation = textBox2.Text;
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
file.Directory.Create();
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
The problem is that it creates a file as "Docs"(where one has to use open with to open the file) and if I am not wrong then its because of the destination path. Could someone please tell what all am I doing wrong.
The source path is retrieved through database!
you need to concat otherwise you're destination location is just the folder not the file path destination
so do something like
var destFile = string.Format(#"{0}\{1}", dstnLocation, Path.GetFileName(sourceLocation));
then copy that
So code becomes
string sourceLocation = textBox2.Text;
string dstnLocation = string.Format(#"C:\Fldr\Docs\{0}", Path.GetFileName(sourceLocation);
if (! System.IO.Directory.Exists(dstnLocation))
{
System.IO.Directory.CreateDirectory(dstnLocation);
}
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
You are creating the file name incorrectly:
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
This creates a file with the name "C:\Fldr\Docs" for example what you want is "C:\Fldr\Docs\myfilename.docx" if I am not mistaken?
Try this instead:
var filename = Path.GetFileName(sourceLocation);
string dstnLocation = Path.Combine(#"C:\Fldr\Docs", filename);
The problem here is that the destination requires an "output" file name.
This problem lies in this line of code
System.IO.File.Copy(sourceLocation, dstnLocation,true);
The dstnLocation needs to be concatenated with the output file name for example:
System.IO.File.Copy(sourceLocation, Path.Combine(dstnLocation,"Database.dbs"),true);