I have been testing my code to save into an XML file locally and it is working fine. However i have just uploaded it to my server and it is not working. I changed the path to the path of the xml file but still no luck. This is my local code...
public void AddNodeToXMLFile(string XmlFilePath, string NodeNameToAddTo)
{
//create new instance of XmlDocument
XmlDocument doc = new XmlDocument();
//load from file
doc.Load(XmlFilePath);
//create main node
XmlNode node = doc.CreateNode(XmlNodeType.Element, "Level", null);
//create the nodes first child
XmlNode mapname = doc.CreateElement("map");
//set the value
mapname.InnerText = mapsave.Value;
// add childes to father
node.AppendChild(mapname);
// find the node we want to add the new node to
XmlNodeList l = doc.GetElementsByTagName(NodeNameToAddTo);
// append the new node
l[0].AppendChild(node);
// save the file
doc.Save(XmlFilePath);
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (mapsave.Value.ToString() == "")
{
lblResult.Text = lblError.Value;
}
else
{
AddNodeToXMLFile("C:\\Users\\Glen.Robson\\Documents\\Visual Studio 2010\\Projects\\Project1\\Project1\\Scripts\\UserMaps.xml", "TileMaps");
}
}
So when i uploaded to the server i changed the path of AddNodeToXMLFile() to:
"http://www.mydomain.com/Scripts/UserMaps.xml"
But this does not work... Can anyone tell me what the file path should be?
You cannot change the path to a URL... the code on the server still needs to know the physical path to the file on the server. It cannot work out where the file is based on a URL.
Why don't you use an application specific path...
AddNodeToXMLFile(VirtualPathUtility.ToAbsolute("~/Scripts/UserMaps.xml"),"TileMaps");
Then in your function, you need to "map" the virtual path into an actual physical path on the server...
public void AddNodeToXMLFile(string XmlFilePath, string NodeNameToAddTo)
{
XmlFilePath = Server.MapPath(XmlFilePath);
...
Also, you need to make sure that permissions are setup on the server correctly - meaning that the process that the ASP.NET application is running on IIS with, has the ability to write to the directly
In a nutshell: What you are asking cannot be done. If you want to change content on your server, you need to have a program or a script on the server that handles your request. Only a program/script that is executed on the server is able to change files on the server.
Related
I have a fileupload control (FileUpload1) in my webform which I use to load an excel file. I use a button called btn_open to display it in a gridview on click.
I also save the file using FileUpload1.SaveAs() method in a server folder.
Now I have another button called btn_edit which on click needs to use the same
file that I just loaded to do another set of operations.
How do I pass this file/file path from btn_open_Click to btn_edit_Click? I do not want to specify the exact location on the code. There will be multiple times I will open new excel files so I don't want to specify the file path to the server for every new file.This needs to happen programatically. Also, I want to avoid using Interop if its possible.
The following code snippet might make things more clear as to what I want to do.
protected void btn_open_Click(object sender, EventArgs e)
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() == ".xlsx" || fileExtension.ToLower() == ".xls")
{
string path = Path.GetFileName(FileUpload1.FileName); //capture the file name of the file I have uploaded
path = path.Replace(" ", ""); // if there is any spacing between the file name it will remove it
FileUpload1.SaveAs(Server.MapPath("~/ExcelFile/") + path); //saves to Server folder called ExcelFile
String ExcelPath = Server.MapPath("~/ExcelFile/") + path; // Returns the physical file path that corresponds to the specified virtual path.
.
.
*code to display it in gridview*
.
.
}
else
{
Console.Writeline("File type not permissible");
}
}
protected void btn_edit_Click(object sender, EventArgs e)
{
//HOW DO I PASS THE ABOVE FILE HERE PROGRAMATICALLY WITHOUT SPECIFYING IT'S EXACT LOCATION ON THE SERVER??
}
Using Session variable helped me solve my problem. Hopefully it will be helpful to other people who might encounter similar issue.
On the first button (in my case btn_open_Click), add:
Session["myXlsPath"] = ExcelFilePath;
Note: "myXlsPath" is just a name I created for my Session variable. ExcelFilePath is the path of my excel file that I want to pass to the other button.
On the button you want to pass the file path to (in my case btn_edit_Click), add:
string ExcelFilePath = (string)Session["myXlsPath"];
I am not sure if I am in the right place to ask this, I am trying to create a table with all the PDF files that I have in a folder into my solution.
And I am trying to retrieve their names and put them in a table to access all of them throughout a link.
I got the following method, however, it not working.
protected void ListFiles()
{
const string MY_DIRECTORY = #"~/HistoricalFiles";
string strFile = null;
foreach (string s in Directory.GetFiles(Server.MapPath(MY_DIRECTORY), "*.*"))
{
strFile = s.Substring(s.LastIndexOf("\\") + 1);
//ListBox1.Items.Add(strFile);
}
}
Is there any way I can access all of them easily and display them in a good way?
By looking at your image, you should change the path of the folder. It is not in your root directory, it is inside Reports\API folder
const string MY_DIRECTORY = #"~/Reports/API/HistoricalFiles";
I am quite confused as to why my code isn't working. I wanted to transfer a textfile that I have into another folder. Here is my code:
private void transferButton_Click(object sender, EventArgs e)
{
string acct = #"C:\\Users\\Accounting\\TicketQueue\\";
string reg = #"C:\\Users\\Registrar\\TicketQueue\\";
if (office == "Registrar")
{
File.Move(reg, acct);
}
else {
File.Move(acct, reg);
}
cleanUp();
}
The office variable is determined beforehand. (Registrar or Accounting)
The cleanup() method is used to clear the entire form and prompt a message that successfully transfers the file.
Everytime I click the button an error displays saying:
Additional information: Could not find file 'C:\Users\Accounting\TicketQueue\'.
You have not actually specified a file name, just a folder location. Do you know the name of the file, or are you trying to transfer the entire folder's contents? Code would need to be something like:
string acct = #"C:\\Users\\Accounting\\TicketQueue\\from.txt";
string reg = #"C:\\Users\\Registrar\\TicketQueue\\to.txt";
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.
I have been writing a small application using C# to copy a document into an individuals 'My Documents' folder on our DMS server.
I've beased the code around the listing provided in the 'WorkSite SDK 8: Utilize the IMANEXT2Lib.IManRefileCmd to File New Document Folders' blog.
Using this code in a WinForm application I have no problems copying the file from the source folder into the users DMS 'My Documents' folder.
However if I use the code in a command line application/.dll or any other type of application (other than WinForm) during the copy process I receive the error messages;
1.
Error occurred when try to log the event!
IManExt: Error occurred when try to log the event!
Access is denied.
2.
The document was imported to the database, but could not be added to
the folder.
IManExt: The document was imported to the database, but could not be
added to the folder.
IManExt.LogRuleEventsCmd.1: Error occurred when try to log the event!
IManExt.LogRuleEventsCmd.1: Access is denied.
Error occurred when try to log the event!
-%-
Does anyone know why I'd receiving the 'Access Denied' error messages when using a non-WinForms application to copy documents?
What would I need to do to get around this issue?
Any help would be amazing!
Code in place:
public void moveToDMS(String servName, String dBName, String foldName)
{
const string SERVERNAME = servName; //Server name
const string DATABASENAME = dBName; //Database name
const string FOLDERNAME = foldName; //Matter alias of workspace
IManDMS dms = new ManDMSClass();
IManSession sess = dms.Sessions.Add(SERVERNAME);
sess.TrustedLogin();
//Get destination database.
IManDatabase db = sess.Databases.ItemByName(DATABASENAME);
//Get destination folder by folder and owner name.
IManFolderSearchParameters fparms = dms.CreateFolderSearchParameters();
fparms.Add(imFolderAttributeID.imFolderOwner, sess.UserID);
fparms.Add(imFolderAttributeID.imFolderName, FOLDERNAME);
//Build a database list in which to search.
ManStrings dblist = new ManStringsClass();
dblist.Add(db.Name);
IManFolders results = sess.WorkArea.SearchFolders(dblist, fparms);
if (results.Empty == true)
{
//No results returned based on the search criteria.
Console.WriteLine("NO RESULTS FOUND!");
}
IManDocumentFolder fldr = null;
if (results.Empty == false)
{
//Assuming there is only one workspace returned from the results.
fldr = (IManDocumentFolder)results.ItemByIndex(1);
}
if (fldr != null)
{
// Import file path
string docPath = #"C:\Temp\";
string docName = "MyWord.doc";
// Create an instance of the ContextItems Collection Object.
ContextItems context = new ContextItemsClass();
// Invoke ImportCmd to import a new document to WorkSite database.
ImportCmd impCmd = new ImportCmdClass();
// The WorkSite object you pass in can be a database, session, or folder.
// Depends on in where you want the imported doc to be stored.
context.Add("IManDestinationObject", fldr); //The destination folder.
// Filename set here is used for easy example, a string variable is normally used here
context.Add("IManExt.Import.FileName", docPath + docName);
// Document Author
context.Add("IManExt.Import.DocAuthor", sess.UserID); //Example of a application type.
// Document Class
context.Add("IManExt.Import.DocClass", "BLANK"); //Example of a document class.
//context.Add("IManExt.Import.DocClass", "DOC"); //Example of a document class.
// Document Description (optional)
context.Add("IManExt.Import.DocDescription", docName); //Using file path as example of a description.
// Skip UI
context.Add("IManExt.NewProfile.ProfileNoUI", true);
impCmd.Initialize(context);
impCmd.Update();
if (impCmd.Status == (int)CommandStatus.nrActiveCommand)
{
impCmd.Execute();
bool brefresh = (bool)context.Item("IManExt.Refresh");
if (brefresh == true)
{
//Succeeded in importing a document to WorkSite
IManDocument doc = (IManDocument)context.Item("ImportedDocument");
//Succeeded in filing the new folder under the folder.
Console.WriteLine("New document number, " + doc.Number + ", is successfully filed to " + fldr.Name + " folder.");
}
}
}
}
Just in case this helps someone else.
It seems my issue was the result of a threading issue.
I noticed the C# winform apps I had created were automatically set to run on a single 'ApartmentState' thread ([STAThread]).
Whereas the console applications & class library thread state and management hadn't been defined within the project and was being handled with the default .NET config.
To get this to work: In the console application, I just added the [STAThread] tag on the line above my Main method call.
In the class library, I defined a thread for the function referencing the IMANxxx.dll and set ApartmentState e.g.
Thread t = new Thread(new ThreadStart(PerformSearchAndMove));
t.SetApartmentState(ApartmentState.STA);
t.Start();
In both cases ensuring single 'ApartmentState' thread was implemented set would resolve the issue.