How to get the path of folder in Azure Function C# - c#

I have created 2 folders in my project named TempFile and TempFile\Sample. Here is the folder structure
How can I get the path of this folder and the file SampleExcel.xlsx (project\TempFile and project\TempFile\Sample\SampleExcel.xlsx resp) using c#. Also once I publish it to Azure will I need to change it?
Here is what I have tried:
public void Run([QueueTrigger("my-queuename", Connection = "")] string myQueueItem, ILogger log)
{
//Method 1
var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
//Method 2
var path = Environment.CurrentDirectory;
//Method 3
var filePath = Path.GetFullPath(#"TempFile\Sample" + "\\SampleExcel.xlsx");
}
The problem with these methods is that they return the path project\bin\Debug\netcoreapp3.1
How can I get the required path?
Any suggestions?

Use Environment.CurrentDirectory as:
filePath1 = Environment.CurrentDirectory +"\\TempFile\\" + tempFile + ".xlsx";
filePath2 = Environment.CurrentDirectory +"\\TempFile\\Sample\\SampleExcel.xlsx";

Related

How can I access a local folder inside a WPF project to load and store files?

I need a library of vector files, where the same files have to be used every time. I want to load them from a folder and have the option to store new ones.
I tried having a library folder inside the WPF project that contains the files:
Solution/Project/Library/file1.dxf
I load them like this:
string currentDir = Directory.GetCurrentDirectory();
var cutOff = currentDir.LastIndexOf(#"\bin\");
var folder = currentDir.Substring(0, cutOff) + #"\Library\";
string[] filePaths = Directory.GetFiles(folder, "*.dxf");
This worked when running on the PC the project was buid, but the program crashes when the .exe is run on another PC. How do I fix this or is there a better approach to this?
Create a subfolder under Environment.SpecialFolder.ApplicationData, read the files in the library folder if it exists. If not create it and save the existing library files to it (here from resources):
string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appFolder + #"\MyAppLibrary\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// Add existing files to that folder
var rm = Properties.Resources.ResourceManager;
var resSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (var res in resSet)
{
var entry = ((DictionaryEntry)res);
var name = (string)entry.Key;
var file = (byte[])rm.GetObject(name);
var filePath = path + name + ".dxf";
File.WriteAllBytes(filePath, file);
}
}
// Load all files from the library folder
string[] filePaths = Directory.GetFiles(path, "*.dxf");
Thanks Jonathan Alfaro and Clemens!

C# : File rename using ASP:NET MVC and IISExpress

I have a utility to rename a file in a specified directory using a certain condition. Running the code using a console application works well and the file is renamed appropriately. However, when I attempt the same in a web application the file is not getting renamed. I am using VS2017 Development Server for the web application debugging.
What am I missing?
Using the console application code as below the file successfully gets renamed :
Rename method:
public static string AddSuffix(string filename, string suffix)
{
string fDir = Path.GetDirectoryName(filename);
string fName = Path.GetFileNameWithoutExtension(filename);
string fExt = Path.GetExtension(filename);
string renamedFilePath = Path.Combine(fDir, String.Concat(fName, suffix, fExt));
return renamedFilePath;
}
Usage in main program:
static void Main(string[] args)
{
string batchperiod = "_70_";
string realPath = #"C:\Users\myuser\source\repos\Solution\Project\BatchIn";
IEnumerable<string> fileList = Directory.EnumerateFiles(realPath);
var CurrentBatchName = (from file in fileList
let fileName = Path.GetFileName(file)
where fileName.Contains(batchperiod)
select fileName).FirstOrDefault();
string absolutePath = (#"C:\Users\myuser\source\repos\Solution\Project\BatchIn\" + CurrentBatchName);
string newPath = Helpers.AddSuffix(absolutePath, String.Format("({0})", Helpers.parameters.IsProcessed));
System.IO.FileInfo fi = new System.IO.FileInfo(absolutePath);
if (fi.Exists)
{
fi.MoveTo(newPath);
}
}
With this code the file is successfully renamed from
GL_Export_70_201907081058.xml
to
GL_Export_70_201907081058(P).xml
The only difference using web application is that the absolutePath is stored in a Session variable .. its derived from a preceding operation/ActionResult :
var absolutePath = (#"C:\Users\myuser\source\repos\Solution\Project\BatchIn\" + CurrentBatchName);
files.FileName = CurrentBatchName;
Session["AbsoluteBatchPath"] = absolutePath;
and later invoked in another ActionResult as :
var sourceFile = Convert.ToString(Session["AbsoluteBatchPath"]);
string newPath = AddSuffix(sourceFile, String.Format("({0})", parameters.IsProcessed));
System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);
if (fi.Exists)
{
// Move file with a new name. Hence renamed.
fi.MoveTo(newPath);
}
What am I missing?
I do suspect there are some permissions I may need to configure when attempting the rename using the Visual Studio Development Server.
Your code see perfect there is no missing ,debug and check whether in MVC your code entered fi.exist if condition..
Please confirmed the same

get file path onto class library project c#

I have a problem when I'll get file path onto class library project.
I have a log4net.config file into my class library project and I need get and read log4net.config. I test many solution:
1
var buildDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filePath = buildDir + #"\log4net.config";
2
var dirPath = Assembly.GetExecutingAssembly().Location;
dirPath = Path.GetDirectoryName(dirPath);
return Path.GetFullPath(Path.Combine(dirPath, "\log4net.config"));
but I don't get any result. please suggest a solution.

Problem with deployment of windows application using setup wizard

I have some xml files, which are used in my application. They are stored in the same folder with application , in subfolder DATA: "C:\MyProject\DATA\".
To get the DATA folder path i use this code :
static public string GetDataFolderPath()
{
string s = System.IO.Directory.GetCurrentDirectory().Replace(#"\bin\Debug", "");
int i = s.LastIndexOf(#"\");
s = s.Substring(0, i);
i = s.LastIndexOf(#"\");
s= s.Substring(0, i);
return s + #"\Data\";
}
So when i want to deploy my application, i create a setup project, and add the DATA folder to Application folder. But after i install the program f.e. "C:\Project"(DATA folder- "C:\Project\DATA" i got the error: "folder C:\DATA is not found".
What i need to change to make things working after deployment. Why it looks for the DATA folder on 1 level higher?
Try this, it might work better:
public static string GetDataFolderPath()
{
#if DEBUG
// This will be executed in Debug build
string path = Directory.GetCurrentDirectory().Replace(#"\bin\Debug", "");
#else
// This will be executed in Release build
string path = Directory.GetCurrentDirectory();
#endif
return Path.Combine(path, "Data");
}
Or just this if you want one for both Debug and Release builds:
public static string GetDataFolderPath()
{
string path = Directory.GetCurrentDirectory().Replace(#"\bin\Debug", "");
return Path.Combine(path, "Data");
}
You have to add using System.IO; for this to work.
Maybe current directory (during launching your program) is not the same one that assemblies lie?
try:
//get the full location of the assembly
string fullPath = System.Reflection.Assembly.GetAssembly(typeof(<your class name>)).Location;
//get the folder that's in
string theDirectory = Path.GetDirectoryName( fullPath );
or
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);

Read & Write Writelog

How do I write the error faced into the log.txt?
Firstly, I get error file name from web config as follows:
string Errorlog = System.Configuration.ConfigurationManager.AppSettings["Errorlog.txt"];
Next, I try to get the full path of the text file; but i do not know which one will pull it out.
This is a few. I want to get the full path by not making it static.
//string path = Global.getLogFilePath();
//string path = Path.GetFileName(directoryFullPath);
//string path = openFileDialog.FileName;
//string path = Path.Combine(System.Environment.CurrentDirectory);
//string path = Path.GetFullPath("Errorlog.txt");
//string path = Directory.GetCurrentDirectory();
//string path = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName());
//string path = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
//string path = Environment.CurrentDirectory.ToString();
//string path = System.Environment.GetEnvironmentVariable("TEMP");
//if (!path.EndsWith("\\")) path += "\\";
Put log.txt in a Logs sub-folder of your web site and then you can get the absolute path like this:
string logFile = HttpContext.Current.Server.MapPath("~/Logs/log.txt");
Also don't forget to restrict the public access to the Logs folder to avoid anyone reading your application log files.

Categories