How to include saved xml file in c# MVC - c#

I have written a method to save xml file to my project.and I run that method automatically in specific time period(once a day(at 3.00 pm)), same file.
but we have to include that file to the project manually.What I want is before xml file save, look if it is exists. if it is exists delete it and save the new one and include it. this is my code.
this is how I save ....
public void sendValue()
{
string wbserviceUrl = "https://someurl.ashx";
WebClient clientOne = new WebClient();
string result = clientOne.DownloadString(wbserviceUrl);
XmlDocument cruisexmlDocument = new XmlDocument();
cruisexmlDocument.LoadXml(result);
cruisexmlDocument.Save("D:/projects/booksmal/XmlFiles/Cruisedata/product.xml");
}
In here I want to check,
1 -check if the file("product.xml") is exist.
2 -if it is exists then delete it and save the new ("product.xml")
3 -then include that file to the project(is this happen automatically when site host)
(Note: save the file is work fine)

string path = Server.MapPath("~/XmlFiles/Cruisedata/product.xml");
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}

Related

How to search for a file extension (.xls) and change it's name? C#

The product I'm using is a Beijer HMI, currently i can generate a report and save it to a known location (my desktop - C:\Users\mrdav\Desktop).
I need to be able to search on my desktop for a file extension .xls and change its name.
When the report is generated by the HMI, it uses the date and time which means when the file is generated the name will be different every time.
On the press of a button i need to search my desktop for the .xls file and change its name to a variable.
// This is my variable with my program
string NewName = Globals.Tags.Tag1.Value;
The code that is generated needs to sit within the below example.
public partial class Screen1
{
void Button1_Click(System.Object sender, System.EventArgs e)
{
// Code to be added here...
}
}
Hopefully someone can help, I’m using windows compact framework so limited on functionality.
Any questions please let me know.
Thanks in advance,
Dave
Here is an example how you can do that:
DirectoryInfo dir = new DirectoryInfo(sExportPath);
FileInfo[] Files = dir.GetFiles("*.csv");
foreach(FileInfo file in Files )
{
// rename file
System.IO.File.Move(file.FullName, GenerateNewFileName());
}
//elsewhere in the class
private string GenerateNewFileName()
{
//here is where you implement creating or getting the filename that you want your file to be renamed to. An example might look like the below
string serialNumber = GetSerialNumber(); //Get the serial number that you talked about in the question. I've made it a string, but it could be an int (it should be a string)
return Path.ChangeExtension(serialNumber,".xls"); //to use path you will need a using statement at the top of your class file 'using System.IO'
}
This seems to work...but i know its not as tidy as it could be.
Any suggestions?
Thanks to all that helped, got there in the end!
void Button_Click(System.Object sender, System.EventArgs e)
{
try
{
// Location for new file
string NewFileName = #"c:\users\mrdav\desktop\testfolder\";
// Add varibale name to new file
NewFileName += Globals.Tags.Tag1.Value;
// add .xls extention to new file
NewFileName += ".xls";
//show new file name to check all ok
MessageBox.Show (NewFileName);
//search for .xls in known directory
DirectoryInfo di = new DirectoryInfo(#"c:\users\mrdav\desktop");
FileInfo[] Files = di.GetFiles("*.xls");
// if files exist with .xls extention
foreach(FileInfo file in Files )
{
// show full file name
MessageBox.Show (file.FullName);
//rename old file to new file name and move to new folder
File.Move(file.FullName, NewFileName);
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}

Create text file in a given folder

I am developing a windows 8 app using Microsoft visual studio 2013. I needed to store the user entered data in a text file. I have wrote the following code segment to create the file and its working. But the text file is created in C:\Users...... I want to create the text file in a given folder. How can I modify my code to create the file in a folder where I specify.
StorageFile sampleFile;
const string fileName = "Sample.txt";
This is how you can create a file in C temp folder
String folderPath = #"C:/temp";
FileStream fs = new FileStream(folderPath + "\\Samplee.txt",FileMode.OpenOrCreate, FileAccess.Write);
As told before, Universal apps are sandboxed which means you can't write a file in an arbitrary folder.
You should take a look at the File access sample on how to do it.
Also, you should take a look at the ApplicationData which gives you a lot of choices for saving user entered data. Is it temporary, do you want it to be synced, is it a setting? There sure is a property that suits your needs.
edit: from http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdata.localfolder.aspx this is what you should do
var applicationData = Windows.Storage.ApplicationData.current;
var localFolder = applicationData.localFolder;
// Write data to a file
function writeTimestamp() {
localFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (sampleFile) {
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
var timestamp = formatter.format(new Date());
return Windows.Storage.FileIO.writeTextAsync(sampleFile, timestamp);
}).done(function () {
});
}
You need to set the directory where you want to save the file.
Try this
string dirctory = #"D:\Folder Name"; //This is the location where you want to save the file
if (!Directory.Exists(dirctory))
{
Directory.CreateDirectory(dirctory);
}
File.WriteAllText(Path.Combine(dirctory, "Sample.txt"), "Text you want to Insert");

Can't load file from path

I have an problem loading an xml from a path, because on my pc(and others) part of the path is mapped:
This is the path i have from the database:
\serverName\files\System\Appldata\Application\3_5\TEST\Program\Version.xml
But on my computer the path looks like this:
Y:\Application\3_5\TEST\Program
This is the code:
var path = new DirectoryInfo(x.LocationName+#"\"+x.FolderName);
var doc = new XmlDocument();
//Loading the file
doc.Load(path.FullName + #"\Version.xml");
Are there any way around this problem?
Well, do not try to concatenate by yourself the path and the filename.
Use Path.Combine
doc.Load(Path.Combine(path.FullName, "Version.xml"));
This requires the using System.IO; at the beginning of your source file.
Of course you could use both the mapped version or the full sharename only if you have the permissions to you remote folder. Also, if your database keeps the full sharename be sure that it is stored with the two initial backslash
EDIT Seeing your edit now, again, do not manually build your paths (and check if the info are valid)
var path = new DirectoryInfo(Path.Combine(x.LocationName, x.FolderName));
if(!path.Exists)
{
MessageBox.Show("Invalid path retrieved:" + path.FullName);
return;
}
var doc = new XmlDocument();
doc.Load(Path.Combine(path.FullName,"Version.xml"));
You are accessing the file using network path. Please make sure that you are able to access the file from the file explorer on webserver.
Try this code:
var doc = new XmlDocument();
var finalPath = Path.Combine(x.LocationName, x.FolderName, "Version.xml");
//Loading the file
doc.Load(finalPath);

Writing to XML using XDocument, but knowing where to write

Hope you can help me a bit. I'm trying to write to an XML file, but am struggling to write the method which, well, writes to the XML file. This is the XML file manually written (using Notepad++ etc.):
<software>
<software_entry
name="Adobe Acrobat X Standard"
path="Applications\Acrobat\Acrobat X Standard\AcroStan.msi"
type="msi"
switches="/qn ALLUSERS=1"
/>
<software_entry
name="Adobe Acrobat X Professional"
path="Applications\Acrobat\Acrobat X Pro\AcroPro.msi"
type="msi"
switches="/qn ALLUSERS=1"
/>
</software>
The aim of this part of the application is to write that using a GUI.
In the application, the user chooses the name of the XML file. It is then saved in the temp folder until further in the process when the user is asked where they would like to save it. Upon entering the desired name of the file and clicking Create, the method called "createAndLoadXML" is run. As its name would suggest, it creates and then loads an XML file (to populate a listview control on the form). Code can be seen below.
private void createAndLoadXML()
{
// Method to create XML file based on name entered by user
string tempPath = Path.GetTempPath();
string configFileName = fileNameTextBox.Text;
string configPath = tempPath + configFileName + ".xml";
// Create XDocument
XDocument document = new XDocument(
new XDeclaration("1.0", "utf8", "yes"),
new XComment("This XML file defines the software selections for use with the Software Installer"),
new XComment("XML file generated by Software Installer"),
new XElement("software",
new XElement("software_entry",
new XAttribute("name", ""),
new XAttribute("path", ""),
new XAttribute("type", ""),
new XAttribute("switches", ""))
)
);
document.Save(configPath);
configCreateLabel.Visible = true;
document = XDocument.Load(configPath);
}
Now, further down this form are 4 text boxes for user input, each relating to the attributes created (name, path, type and switches) The idea is the user will write in these text boxes, click an 'Add' button and then the program will write those 4 fields as attributes to this XML file. So far, I have this code, which is horribly incomplete and doesn't even use LINQ to XML.
private void writeToXML()
{
// Method to write lines to XML file based on user input
// Sets string variables
string fileName = softwareNameTextBox.Text;
string filePath = filePathTextBox.Text;
string fileType = installerType.Text.ToString();
string installSwitches = installSwitchesTextBox.Text;
using (XmlWriter xw = XmlWriter.Load(configPath)) //This line is wrong, I know
{
xw.WriteStartElement("software");
xw.WriteElementString("name", fileName);
xw.WriteElementString("path", filePath);
xw.WriteElementString("type", fileType);
xw.WriteElementString("switches", installSwitches);
xw.WriteEndElement();
}
}
Basically, could anyone please help me with the above method which writes to the XML the data the user has entered into the text box controls? I'm not sure how to load the previously created XML document (from my createAndLoadXML method), and how to write within the root element (software) using LINQ to XML.
Try this out. I think this should get you what you want assuming the XML exists beforehand since you are calling createAndLoadXML before this method. I wrote this in NotePad++, so I may have a error or two.
private void writeToXML()
{
// Method to write lines to XML file based on user input
// Sets string variables
string fileName = softwareNameTextBox.Text;
string filePath = filePathTextBox.Text;
string fileType = installerType.Text.ToString();
string installSwitches = installSwitchesTextBox.Text;
string FILE_PATH = "bla.xml";
XDocument xDoc = XDocument.Load(FILE_PATH);
xDoc.Root.Add(new XElement("software_entry",
new XAttribute("name", fileName),
new XAttribute("path", filePath),
new XAttribute("type", fileType),
new XAttribute("switches", installSwitches)
));
xDoc.Save(FILE_PATH);
}

Generate a filename with number inside parenthesis

I'm working with asp.net project where user can upload files to server. I want to save the file with its original name, but if file with the same name already exists How can I generate a filename with a number in the parenthesis like windows does?
Files are uploaded to a particular folder and saved with its client side name itself. So, If a file named myimage.jpg is uploaded and a file with same name already exists in the server, I need to rename it to myimage(1).jpg or if 'myimage.jpg' to 'myimage(n).jpg' exists, I need to rename it to myimage(n+1).jpg.
What will be the best way to search for and generate such file names? My first guess was to use linq with regex over DirectoryInfo.EnumerateFiles(), but is that a good approach?
If the files with same orginal name don't have to be shown sorted by upload date/time, you could simply append System.Guid.NewGuid().ToString() to the file name.
public static object lockObject = new object();
void UploadFile(...)
{
//-- other code
lock (lockObject)
{
int i = 1;
string saveFileAs = "MyFile.txt";
while (File.Exists(saveFileAs))
{
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(saveFileAs);
string ext = Path.GetExtension(saveFileAs)
saveFileAs = String.Concat(fileNameWithoutExt, "(", i.ToString(), ")", ext);
i++;
}
//-- Now you can save the file.
}
}
You don't need LINQ or regex.
If the original filename exists, append (1) to the name.
If that exists, append (2) to the (original) name.
And so on...

Categories

Resources