c# - How to assign resources folder to a string - c#

I'm currently using this,
string finename = "text.txt"; //setting file name
//setting locations
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filepath = #"C:\User\Users\Documents\Files\Apple"; // <--- need to use Resources folder in the project folder here
//filename and location combining to be copied
string source = Path.Combine(filepath,filename);
string destination = Path.Combine(path,filename);
if (something=1)
{
File.Copy(source,destination, true); //copying
}
I've added all the files to the Resources now i need to refer to Resources folder instead of "filepath" here,
is there any way to assign the resources folder (& its contents) to a string so i can simply change the location? then i can use this code on other PC's also.
Edit -
Imagine i have orange,mango and apple folder inside the resource folder, and each of these 3 folders contain a text file with the name "text.txt".
And i need to copy one of these text files from each & every fruit folder on request & paste it on desktop.
Now i need to store the location of "Resources\apple" , "Resources\orange" & "Resources\mango" on 3 different strings so i can simply call them in the "string source = Path.Combine(filepath,filename)" part instead of older "filepath" to copy those text files from any of the fruit folder inside resources folder to the desktop.
thanks.

Get src or root folder path.
Combine root folder path with your resource folder path.
Combine result(root\resources) with your file name
Here you go, you will get exact path of file and now you can copy it to the destination.
Here is the implementation: This code is running on my machine.
/// <summary>
/// Here you just need to send fruit name
/// </summary>
/// <param name="fruitName">Name of fruit</param>
public void CopyFile(string fruitName)
{
string filename = "text.txt"; //setting file name
string resouceFolderName = Path.Combine("Resources", fruitName);
//Destination Path
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//CurrentDirectory return src\\Bin\\Debug so extracting src root folder path
string parentFolderPath = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName).FullName;
//combining parent folder path with resource folder name
string folderPath = Path.Combine(parentFolderPath, resouceFolderName); // <--- need to use Resources folder in the project folder here
//Checking if exist or not
if (!Directory.Exists(folderPath) || !Directory.Exists(path))
{
Console.WriteLine("Error");
return;
}
//filename and location combining to be copied
string source = Path.Combine(folderPath, filename);
string destination = Path.Combine(path, filename);
if (true)
{
File.Copy(source, destination, true); //copying
}
}
Note: Here I used test.txt and Resources string as a constant considering they won't change

Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
What you are doing here is retrieving the path to your desktop and copying your .txt file from your filepath to there.
You are not copying the file onto your project "Resources" folder.
In case your file is there as #Prasad telkikar said, with the following code you would have the path to your's "Resource" folder and be able to access all the content inside it.
string path = Path.Combine(Environment.CurrentDirectory, "Resources");

Related

Copying a file from one location into a folder in Solutions Explorer using asp.net

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
}
}

Get the filename of a file that was created through ZipFile.ExtractToDirectory()

string zipPath = #"D:\books\"+fileinfo.DccFileName;
string extractPath = #"D:\books";
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
This is a simple piece of code that does exactly what i want it to do: Gets a zip file from d:\books and unzips it into the same directory. Is there any way i can read the filename of the newly created file (considering that there is only one file in the .zip archive). I would prefer a solution that does not involve reading changes in the directory since other files might be created in it at the same time of the unzip.
You can construct the path by inspecting the archive
var intentedPath = string.Empty;
//open archive
using (var archive = ZipFile.OpenRead(zipPath)) {
//since there is only one entry grab the first
var entry = archive.Entries.First();
//the relative path of the entry in the zip archive
var fileName = entry.FullName;
//intended path once extracted would be
intentedPath = Path.Combine(extractPath, fileName);
}

How to move subfolder with files to another directory in asp.net C#

I want to copy and paste sub-folders of source folder ABC To destination folder. But it is not working. Here is my C# code, it work's fine but it copies the whole folder instead of only the sub-folders.
// string fileName = "test.txt";
string sourcePath = "D:\\Shraddha\\Demo_Web_App\\Source";
string targetPath = "D:\\Shraddha\\Demo_Web_App\\Destination";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath);
string destFile = System.IO.Path.Combine(targetPath);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
// System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
//fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
Alright, here we go:
This doesn't really makes sense. If targetPath exists, create targetPath folder?
if (System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
You probably meant:
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
What you need to do first is, getting all directories to begin with:
var allDirectories = Directory.GetDirectories(targetPath, "*", SearchOption.AllDirectories);
then you can loop through allDirectories with foreach, find all files in each folder and copy the contents.
The following line cannot work like provided:
destFile = System.IO.Path.Combine(targetPath);
File.Copy expects a path to a file where you want to copy the content from "s", but you are providing only the destination folder. You have to include a filename in the Path.Combine method.
If you parse the path strings with the Path.GetFileName method for example, you can pass the result (only the filename without full source path) as an additional argument to Path.Combine to generate a valid destination path.
Additionally, like uteist already said, you have to get all subdirectories first, because in your code example, you're only copying the files, directly placed under your root source folder.
To keep the Directory structure
foreach (var dir in System.IO.Directory.GetDirectories(sourcePath))
{
var dirInfo = new System.IO.DirectoryInfo(dir);
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(targetPath, dirInfo.Name));
foreach (var file in System.IO.Directory.GetFiles(dir))
{
var fileInfo = new System.IO.FileInfo(file);
fileInfo.CopyTo(System.IO.Path.Combine(targetPath, dirInfo.Name, fileInfo.Name));
}
};

Copy a specific file (.docx, .pdf, .pptx etc) form folder in C#

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);

C# absolute path with streamReader

I have an issue with the reading a file in C#
I have two different locations for .exe (both different) and reading the same .xml file. So when I give the path like this:
TextReader textReader = new StreamReader(#"../../../TrajectoryGen/obstacleList.xml");
it is able to read from one location ( which is 3 folders behind as used in the path) but not from another location (which is only 2 folders behind)
How do I fix this problem so that it works from both folders?
First way, this relies on you knowing one of the parent folder's names.
const string FILENAME = "obstacleList.xml";
const string FOLDER = "TrajectoryGen";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
do
{
path = Path.GetDirectoryName(path);
} while (!Path.GetFileName(path).Equals(FOLDER, StringComparison.OrdinalIgnoreCase));
string filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
^^ You can also use a partial path in the FILENAME like the example below incase you need to into directories once you are at your "base" folder that you know the name of.
Second way blindly continues up directories
const string FILENAME = #"TrajectoryGen\obstacleList.xml";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
string filepath;
do
{
path = Path.GetDirectoryName(path);
//pump
filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
} while (!File.Exists(filepath));
Both require "using System.IO;" and both have no error handling implemented and will throw NullReferenceException if the file/folder is not found.
I purposely used the do-while loop because the definition of path will included the executable name.

Categories