How to delete the xmldocument saved in particular place - c#

I have the following code where i save the xml file into this particular location shown below
public bool GetList(string keyword1, string streetname, string lat, string lng, string radius)
{
XmlDocument xmlDoc= CreateXML( keyword1,streetname,lat,lng,radius);
xmlDoc.Save(#"C:\Documents and Settings\Vijay.EKO-03\Desktop\blockseek3-9-2010\Block3.xml");
return true;
}
This Block3.xml file gets stored in my application folder, i refer to that particular Block3.xml using this code
function searchLocationsNear()
{
var searchUrl = "Block3.xml";
GDownloadUrl(searchUrl, function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
I am able to parse that Block3.xml and display results but my problem is during second iteration again when i try to save Block3.xml
xmlDoc.Save(#"C:\Documents and Settings\Desktop\blockseek3-9-2010\Block3.xml");
The previous Block3.xml file gets replaced by new one and gets stored in application folder
when i execute var searchUrl="Block3.xml"; it reads the first Block3.xml not the replaced one ,can any one help to tackle this code .
Is their any syntax to clear the saved xmldoc file in that particular folder .

Most likely, the GXml class retains an open file handle. Check the documentation: if it implements IDisposable, wrap your processing code like this:
using ( var xml = GXml.parse(data) )
{
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
}
This also assumes that the parse() method is the one that actually loads and reads the file. If you don't release the file handle, your process doesn't know that there's another version in the file system. (And other nasty stuff can happen, depending on the exact mode the O/S opened the file in.)
I trust your production code won't contain these hard coded paths...?

Related

Export Warning async task in for loop

I have the method here http://teocomi.com/export-revit-warnings-list-from-api/ and am calling it from an application macro method to export warnings for a folder of rvt files:
public async void ExportWarningHTML()
{
Autodesk.Revit.UI.UIApplication uiapp = this;
Document doc = uiapp.ActiveUIDocument.Document;
// Input Directory
string inputDir = #"C:\input";
// Output Directory
string outputDir = #"C:\output";
//Get files from inputDir
string[] files = Directory.GetFiles(inputDir, "*.rvt");
// Set open options to detach from central and preserve ws
OpenOptions openOptions = new OpenOptions();
openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets;
// Process each *.rvt file in folder
// Naive approach. DOES NOT WORK.
foreach(string file in files)
{
// Get current doc
var docLast = uiapp.ActiveUIDocument.Document;
// Open new document
var docNext = ActiveUIDocument.Application.OpenAndActivateDocument(file);
// Close last document
docLast.Close(false);
// Export Warnings
var html = await Win32Api.ExportWarinings(uiapp, outputDir);
}
}
}
However this only works for the first file then crashes. How can I modify this code or the linked "ExportWarnings" code I linked to to have this process a folder of .rvt files.
Congratulations on your very nice solution to Export Revit Warnings List From Api!
As you know, the Revit API can only be used within a valid Revit API context. Such a context is provided only within callback functions provided by the Revit API, such as external command Execute. Furthermore, the Revit API is not multi-threading. Making calls to the API outside such a context can lead to a crash. That may well be exactly what you are experiencing.
Therefore, I wonder whether async can be used at all in this context. One possibility to handle these restrictions is by making use of external events:
http://thebuildingcoder.typepad.com/blog/about-the-author.html#5.28
Is this code running in an external command Execute method? If so, how about just removing the async stuff, and simply calling Sleep repeatedly until Revit has finished processing the first file?
No, that will probably not work, and is probably not right at all.
Next suggestion: remove async; make the call to process the next file; when it is done, raise an external event; within the external event, repeat the algorithm to process the next file; etc.
I am very much looking forward to hearing how you resolve this!

Use uploaded file instead of local file to read content

Im working on a Discord bot and want to create this:
I have a string that reads the content of a local file, but I want to upload that file to a specific website (for example GitHub) and use it, instead of the local file (basically, I want to get rid of the local file and be able to use the uploaded file).
I have this simple line of code:
string[] contentFile = File.ReadAllLines("files/file.txt");
Can somebody help me out here?
Edit: The file contains the lines "1", "2", "3" (and so on), and I want to put these lines in a string array so that I can get access to "1" with contentFile[0], to "2" with contentFile[1] and so on and so forth. It works perfect with a local file, but I do not know how to get access to the uploaded file and the lines within.
So this is how I got it to work (if anyone is interested):
using (var client = new WebClient())
{
client.DownloadFile("www.website.com/file.txt", "files/file.txt");
}
string[] fileContent = File.ReadAllLines("files/file.txt");
while (true)
{
try
{
if (File.Exists("files/file.txt")) File.Delete("files/file.txt");
break;
}
catch (IOException)
{
codeTrue = true;
}
}
This basically downloads the file, reads it and deletes it afterwards. The only "problem" is that everytime I update the file on the website, I need to restart the application, else the string array wont be updated. You can solve that problem by adjusting the code a bit and creating an update-loop.

Read .txt embedded as resource

I have embedded a resource into my code, I want to read the text and apply the text to some string variables. I have worked out how to do that when I use an external file but I only want the .exe
string setting_file = "config.txt";
string complete = File.ReadAllText(setting_file);
string Filename = complete.Split('#').Last(); //"Test.zip";
string URL = complete.Split('#').First();
How can I read the resource config.txt
(Preferably without new procedures)
The File class is only used for accessing the file system whereas your file is no longer in the system so this line needs to change. As others have hinted with linked answers you need to get the stream for the resource and then read that. The below method can be called to replace your File.ReadAllText method call.
private static string GetTextResourceFile(string resourceName)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
The resourceName will be something along the lines of MyNamespace.Myfile.txt. If you are having problems finding your resourcename then the method GetManifestResourceNames on the assembly will help you identify it while debugging.
Also of note is the above method will throw an exception if the resource isn't found. This should be handled in real code but I didn't want to confuse the above sample with standard error handling code.
See also How to read embedded resource text file for a different question with the same answer (that differs in that it asks only about streams but in fact streams seem to be the only way to access embedded resource files anyway).
This is how you can use embedded files Properties.Resources.yourfilename

Reset Application setting in wp7

I have created an app that initially creates a database and saves some data in it.
Now I want to delete this database and its files when the user clicks on the reset button but I am getting an error – 'this is use in another process'. I want it to delete and recreate the database when click on the reset button. Any ideas?
The most frequent cause of this is ude to the thread unsafe nature of interacting with isolated storage on Windows Phone. Regardless of how you're implementing the database (be it in a file, or series of files), you're interacting with the isolated storage on some level.
I highly encourage you to read, and make sure you understand this overview of isolated storage before going too far.
You're remark:
This is in use in another process
makes me think you're using a third party library to do your database stuff. This exception/error is being thrown when the library itsself is unable to access isolated storage. Without knowing exactly how you're implementing the database, it's hard to be exactly speak to your situation.
You never "recreate IsolatedStorage", Isolated Storage is a term used to define the collection of disk space your application has access to. Much like a folder, this disk space has a root, and contains only files that you create.
In order to avoid thread exceptions when accessing Isolated Storage, make sure you use the using keyword in C# like so:
namespace IsolatedStorageExample
{
public class ISOAccess
{
// This example method will read a file inside your Isolated Storage.
public static String ReadFile(string filename)
{
string fileContents = "";
// Ideally, you should enclose this entire next section in a try/catch block since
// if there is anything wrong with below, it will crash your app.
//
// This line returns the "handle" to your Isolated Storage. The phone considers the
// entire isolated storage folder as a single "file", which is why it can be a
// little bit of a confusing name.
using(IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForAppliaction())
{
// If the file does not exist, return an empty string
if(file.Exists(filename))
{
// Obtain a stream to the file
using(IsolatedStorageFileStream stream = File.OpenFile(filename, FileMode.Open)
{
// Open a stream reader to actually read the file.
using(StreamReader reader = new StreamReader(stream))
{
fileContents = reader.ReadToEnd();
}
}
}
}
return fileContents;
}
}
}
That should help with your problem of thread safety. To be more specifically helpful toward what you want to do, take a look at the following methods (you can add this to the above class):
// BE VERY CAREFUL, running this method will delete *all* the files in isolated storage... ALL OF THEM
public static void ClearAllIsolatedStorage()
{
// get the handle to isolated storage
using(IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
// Get a list of all the folders in the root directory
Queue<String> rootFolders = new Queue<String>(file.GetDirectoryNames());
// For each folder...
while(0 != rootFolders.Count)
{
string folderName = rootFolders.Dequeue();
// First, recursively delete all the files and folders inside the given folder.
// This is required, because you cannot delete a non-empty directory
DeleteFilesInFolderRecursively(file, folderName);
// Now that all of it's contents have been deleted, you can delete the directory
// itsself.
file.DeleteDirectory(rootFolders.Dequeue());
}
// And now we delete all the files in the root directory
Queue<String> rootFiles = new Queue<String>(file.GetFileNames());
while(0 != rootFiles.Count)
file.DeleteFile(rootFiles.Dequeue());
}
}
private static void DeleteFilesInFolderRecursively(IsolatedStorageFile iso, string directory)
{
// get the folders that are inside this folder
Queue<string> enclosedDirectories = new Queue<string>(iso.GetDirectoryNames(directory));
// loop through all the folders inside this folder, and recurse on all of them
while(0 != enclosedDirectories.Count)
{
string nextFolderPath = Path.Combine(directory, enclosedDirectories.Dequeue());
DeleteFilesInFolderRecursively(nextFolderPath);
}
// This string will allow you to see all the files in this folder.
string fileSearch = Path.Combine(directory, "*");
// Getting the files in this folder
Queue<string> filesInDirectory = iso.GetFileNames(fileSearch);
// Finally, deleting all the files in this folder
while(0 != filesInDirectory.Count)
{
iso.DeleteFile(filesInDirectory.Dequeue());
}
}
Another thing I highly recommend is implementing the class that accesses IsolatedStorage using a "Multithreaded Singleton Pattern" as described here.
Hope that's helpful. Code is provided "as-is", I have not compiled it, but the general concepts are all there, so if there's something amiss, read the MSDN docs to see where I goofed. But I assure you, most of this is copied from functional code of mine, so it should work properly with very little fanagaling.

C#: How do you handle/parse messages for your applications like drag and dropping an associated file type?

C#: How do you handle/parse messages for your applications like drag and dropping an associated file type?
Let's say I have a text document application and I want it to execute and open a file if,
1.) a .txt document is dragged on top of the exe.
How could I make that possible, to execute the text software, and two, finally open and display the text document in the text document software?
You have to find where your Main method is declared to be sure its signature includes the args parameter, then you can check upon args array and you will find the complete pathname of the file dragged on your application's exe. Now you can then work with it accordingly to your needs.
Example:
static void Main(String[] args)
{
string p = args[0];
string e = Path.GetExtension(p);
if (e == ".txt")
{
// It's a text file
}
}
You can also drag more than a file and find their names inside the same array.
Remember that in my example i don't check if there are actually some elements in args array and thus i can get an IndexOutOfBoundException if nothing is dragged (or passed as argument) when launching the application and finally that using Path.GetExtension method doesn't assure you the file is what you think, but just it has that extension.
When someone drags-and-drops a text file on your application's executable, your app will get started and the path of the text file will be passed as a parameter. You should be able to examine it in your Main method.

Categories

Resources