Save XML File in Project Folder - c#

try
{
XElement contactsFromFile = XElement.Load("App_Data/EmployeeFinList.xml");
var xEle = new XElement("Employees",
from emp in ListFromBasicPay
select new XElement("Employee",
new XAttribute("EmpID", emp.employee_personal_id),
new XElement("GrandTotal", emp.grandTotal),
new XElement("Housing", emp.housing),
new XElement("BasePay", emp.base_pay),
new XElement("XchangeRate", emp.Exchange_rate)));
xEle.Save("..\\changesetDB.xml");
Debug.WriteLine("Converted to XML");
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
I want to save the xml file in a folder i created in my project. I will then use that xml file created in my folder and read and write from it. Any idea how to do it?

Use System.Reflection.Assembly.GetExecutingAssembly().Location
To get the full path of you assembly, Combine that with System.IO.Path.GetDirectoryName().
That would be like:
String path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
xEle.Save(path + #"\myfilename.xml");
Though you should note that if your application is installed in C:\Program Files for example, you'll need some sort of elevation permissions to be able to write there depending on the security settings of the machine your app has been deployed on. It is best to always have a work directory in some other location like (Application Data) for example..

Use Red Serpent's answer for getting your project's folder:
String path = System.IO.Path.GetDirectoryName
(System.Reflection.Assembly.GetExecutingAssembly().Location);
Then use:
string mySavePath = Path.Combine(path, myFolder);
string myXMLPath = Path.Combine(SavePath,"changesetDB.xml");
You can then use myXMLPath to read and write from XML file you just created.

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!

Cannot move a file to another folder. Error returns on a wrong path

Here's my code in moving excel file to be specific..
if (Directory.GetFiles(destinationPath, "*.xls").Length != 0)
{
//Move files to history folder
string[] files = Directory.GetFiles(destinationPath); //value -- D://FS//
foreach (string s in files)
{
var fName = Path.GetFileName(s); //12232015.xls
var sourcePath = Path.Combine(destinationPath, fName);
var destFile = Path.Combine(historyPath, fName); // -- D://FS//History
File.Move(fName, destFile);
}
}
But it gets an error of
Could not find file 'D:\Project\ProjectService\bin\Debug\12232015.xls'.
Why it finds under my project not on the specific folder i set?
Thank you.
You're only using the name of the file:
var fName = Path.GetFileName(s); //12232015.xls
//...
File.Move(fName, destFile);
Without a complete path, the system will look in the current working directory. Which is the directory where the application is executing.
You should use the entire path for the source file:
File.Move(sourcePath, destFile);
Explicitly specifying the full path is almost always the best approach. Relative paths are notoriously difficult to manage.
There is an Logical error. Change
File.Move(fName, destFile);
to
File.Move(sourcePath, destFile);
as fName only contains file name and not fullpath. The file is checked in working directory.

C# connect to IIS Server and compare Server Website folder and Client Folder on local Machine

How to connect server already hosted on IIS Website Folder and compare the Local Client Folder?
This is my Website URL on localhost
IISHostedWebsite/Updates //Folder in Website
I need to compare in this url update folder files with my local client machine's D:\Updates folder.
If new updates available into server it will copy to my D:\Updates folder.
How can we achieve this sort of situation ?
I have some code that in C#
var directory = new DirectoryInfo(#"D:\\Anand\\Work\\FolderCheck\\Server");
var myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
This code generates the latest updated file from folder
The MSDeploy tool (http://www.iis.net/downloads/microsoft/web-deploy) was designed to solve this problem. It lets you compare IIS virtual directories to other directories, and synchronize them if needed. It can also be used just as a diff tool.
In your example, after installing MSDeploy, you could do the following:
msdeploy.exe -verb:sync -source:contentPath="IISHostedWebSite/Updates" -dest:contentPath=d:\updates -whatIf
This command will show the list of changes needed to update d:\updates to look like IISHostedWebSites/Updates. If you remove the "-whatif" it will actually do the changes.
You can also call the MSDeploy programatically to do the same thing.
Also the problem with your code snippet is that you wouldn't detect deleted files from source that also need to be deleted from destination.
Here my code is for Getting Files from Directory and Check Whether are same if not It will Showing No updates Found and After that It will Check latest Files Available into Folder if Available then Copy this Files and Move to Destination Folder This is my Task but i have completed my code in Latest updated file i get from this code but i dont no how this files are copy into destination folder
string serverPath = #"D:\Anand\Work\FolderCheck\Server"; //Source File
string clientPath = #"D:\Anand\Work\FolderCheck\Client"; //destination Folder
private static bool CompareFileSizes(string fileServer, string fileClient)
{
bool fileSizeEqual = true;
if (fileServer.Length == fileClient.Length) // Compare file sizes
{
fileSizeEqual = false; // File sizes are not equal therefore files are not identical
}
return fileSizeEqual;
}
try
{
if (!File.Exists(serverPath) || !File.Exists(clientPath))
{
try
{
var Server = Path.GetFileName(serverPath);
var Client = Path.GetFileName(clientPath);
string ServerFile = Server.ToString();
string ClientFile = Client.ToString();
if (CompareFileSizes(ServerFile, ClientFile))
{
lblServerMsg.Text = "No Updates are Found: ";
}
else
{
var directoryServer = new DirectoryInfo(#"D:\Anand\Work\FolderCheck\Server"); //check latest Available File From Server
var myFile = (from f in directoryServer.GetFiles()
orderby f.LastWriteTime descending
select f).First();
lblServerMsg.Text = "Updates Are Available Click for Update Button:";
btnCheckUpates.Visible = false;
btnUpdates.Visible = true;
}
}
catch (Exception msg)
{
lblServerMsg.Text = "No Updates are Found: " + msg.Message;
}
}
else
{
throw new FileNotFoundException();
}
}
catch (FileNotFoundException ex)
{
lblServerMsg.Text = ex.Message;
}
Above code i have done Get latest File from Source Folder but i dont no how to
var myFile = (from f in directoryServer.GetFiles()
orderby f.LastWriteTime descending
select f).First();
Above doe myFile are latest File from Source Folder this i want to copy into Destination Folder

Can I write a file to a folder on a server machine from a Web API app running on it?

I have this code in my Web API app to write to a CSV file:
private void SaveToCSV(InventoryItem invItem, string dbContext)
{
string csvHeader = "id,pack_size,description,vendor_id,department,subdepartment,unit_cost,unit_list,open_qty,UPC_code,UPC_pack_size,vendor_item,crv_id";
int dbContextAsInt = 0;
int.TryParse(dbContext, out dbContextAsInt);
string csvFilename = string.Format("Platypus{0}.csv", dbContextAsInt);
string csv = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}", invItem.ID,
invItem.pksize, invItem.Description, invItem.vendor_id, invItem.dept, invItem.subdept, invItem.UnitCost,
invItem.UnitList, invItem.OpenQty, invItem.UPC, invItem.upc_pack_size, invItem.vendor_item, invItem.crv_id);
string existingContents;
using (StreamReader sr = new StreamReader(csvFilename))
{
existingContents = sr.ReadToEnd();
}
using (StreamWriter writetext = File.AppendText(csvFilename))
{
if (!existingContents.Contains(csvHeader))
{
writetext.WriteLine(csvHeader);
}
writetext.WriteLine(csv);
}
}
On the dev machine, the csv file is saved to "C:\Program Files (x86)\IIS Express" by default. In preparation for when it is deployed to its final resting/working place, what do I need to do to get the file to save, e.g., to the server's "Platypi" folder - anything special? Do I have to specifically set certain folder persimmons to allow writing to "Platypi."
Is it simply a matter of changing this line:
string csvFilename = string.Format("Platypus{0}.csv", dbContextAsInt);
...to this:
string csvFilename = string.Format(#"\Platypi\Platypus{0}.csv", dbContextAsInt);
?
In the case of the IIS folder the application has rights to write in there. I suggest to write files to the App_Data folder.
When you want to save files outside the IIS application folder you have to give the service account of the IIS application pool (I think it by default is NETWORKSERVICE) the appropriate rights on that folder.
As requested by B. Clay Shannon my implementation:
string fullSavePath = HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Platypus{0}.csv", dbContextAsInt));
Thanks to Patrick Hofman; this is the exact code I am using, and it is saved to the project's App_Data folder:
public static string appDataFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
. . .
string csvFilename = string.Format("Platypus{0}.csv", dbContextAsInt);
string fullSavePath = string.Format("{0}{1}", appDataFolder, csvFilename);

Moving files based on name to the corresponding folder

Hello everyone and well met! I have tried a lot of different methods/programs to try and solve my problem. I'm a novice programmer and have taken a Visual Basic Class and Visual C# class.
I'm working with this in C#
I started off by making a very basic move file program and it worked fine for one file but as I mentioned I will be needing to move a ton of files based on name
What I am trying to do is move .pst (for example dave.pst) files from my exchange server based on username onto a backup server in the users folder (folder = dave) that has the same name as the .pst file
The ideal program would be:
Get files from the folder with the .pst extension
Move files to appropriate folder that has the same name in front of the .pst file extension
Update:
// String pstFileFolder = #"C:\test\";
// var searchPattern = "*.pst";
// var extension = ".pst";
//var serverFolder = #"C:\test3\";
// String filename = System.IO.Path.GetFileNameWithoutExtension(pstFileFolder);
// Searches the directory for *.pst
DirectoryInfo sourceDirectory = new DirectoryInfo(#"C:\test\");
String strTargetDirectory = (#"C:\test3\");
Console.WriteLine(sourceDirectory);
Console.ReadKey(true);>foreach (FileInfo file in sourceDirectory.GetFiles()) {
Console.WriteLine(file);
Console.ReadKey(true);
// Try to create the directory.
System.IO.Directory.CreateDirectory(strTargetDirectory);
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}
This is just a simple copy procedure. I'm completely aware. The
Console.WriteLine(file);
Console.ReadKey(true);
Are for verification purpose right now to make sure I'm getting the proper files and I am. Now I just need to find the folder based on the name of the .pst file(the folder for the users are already created), make a folder(say 0304 for the year), then copy that .pst based on the name.
Thanks a ton for your help guys. #yuck, thanks for the code.
Have a look at the File and Directory classes in the System.IO namespace. You could use the Directory.GetFiles() method to get the names of the files you need to transfer.
Here's a console application to get you started. Note that there isn't any error checking and it makes some assumptions about how the files are named (e.g. that they end with .pst and don't contain that elsewhere in the name):
private static void Main() {
var pstFileFolder = #"C:\TEMP\PST_Files\";
var searchPattern = "*.pst";
var extension = ".pst";
var serverFolder = #"\\SERVER\PST_Backup\";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, searchPattern)) {
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Gets the user name based on file name
// e.g. DaveSmith.pst would become DaveSmith
var userName = theFileInfo.Name.Replace(extension, "");
// Sets up the destination location
// e.g. \\SERVER\PST_Backup\DaveSmith\DaveSmith.pst
var destination = serverFolder + userName + #"\" + theFileInfo.Name;
File.Move(file, destination);
}
}
System.IO is your friend in this case ;)
First, Determine file name by:
String filename = System.IO.Path.GetFileNameWithoutExtension(SOME_PATH)
To make path to new folder, use Path.Combine:
String targetDir = Path.Combine(SOME_ROOT_DIR,filename);
Next, create folder with name based on given fileName
System.IO.Directory.CreateDirectory(targetDir);
Ah! You need to have name of file, but with extension this time. Path.GetFileName:
String fileNameWithExtension = System.IO.Path.GetFileName(SOME_PATH);
And you can move file (by File.Move) to it:
System.IO.File.Move(SOME_PATH,Path.Combine(targetDir,fileNameWithExtension)
Laster already show you how to get file list in folder.
I personally prefer DirectoryInfo because it is more object-oriented.
DirectoryInfo sourceDirectory = new DirectoryInfo("C:\MySourceDirectoryPath");
String strTargetDirectory = "C:\MyTargetDirectoryPath";
foreach (FileInfo file in sourceDirectory.GetFiles())
{
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}

Categories