I am using Visual Studio C# to parse an XML document for a file location from a local search tool I am using. Specifically I am using c# to query if the user has access to certain files and hide those to which it does not have access. I seem to have files that should return access is true however because not all files are local (IE some are web files without proper names) it is not showing access to files it should be showing access to. The error right now is caused by a url using .aspx?i=573, is there a work around or am I going to have to just remove all of these files... =/
Edit: More info...
I am using right now....
foreach (XmlNode xn in nodeList)
{
string url = xn.InnerText;
//Label1.Text = url;
try
{ using (FileStream fs = File.OpenRead(url)) { }
}
catch { i++; Label2.Text = i.ToString(); Label1.Text = url; }
}
The issue is, when it attempts to open files like the ....aspx?i=573 it puts them in the catch stack. If I attempt to open the file however the file opens just fine. (IE I have read access but because of either the file type or the append of the '?=' in the file name it tosses it into the unreadable stack.
I want everything that is readable either via url or local access to display else it will catch the error files for me.
I'm not sure exactly what you are trying to do, but if you only want the path of a URI, you can easily drop the query string portion like this:
Uri baseUri = new Uri("http://www.domain.com/");
Uri myUri = new Uri(baseUri, "home/default.aspx?i=573");
Console.WriteLine(myUri.AbsolutePath); // ie "home/default.aspx"
You cannot have ? in file names in Windows, but they are valid in URIs (that is why IE can open it, but Windows cannot).
Alternatively, you could just replace the '?' with some other character if you are converting a URL to a filename.
In fact thinking about it now, you could just check to see if your "document" was a URI or not, and if it isn't then try to open the file on the file system. Sounds like you are trying to open any and everything that is supplied, but it wouldn't hurt to performs some checks on the data.
private static bool IsLocalPath(string p)
{
return new Uri(p).IsFile;
}
This is from Check if the path input is URL or Local File it looks like exactly what you are looking for.
FileStream reads and writes local files. "?" is not valid character for local file name.
It looks like you want to open local and remote files. If it is what you are trying to do you should use approapriate metod of downloading for each type - i.e. for HTTP you WebRequest or related classes.
Note: it would be much easier to answer if you'd say: when url is "..." File.OpenRead(url) failes with exception, mesasge "...".
Related
I am trying to run the File.Copy function so that I can use a template file I have to make a new word document that the code will fill out. Whenever the code gets to the file.copy function I get the error
"IOException: The filename, directory name, or volume label syntax is incorrect : 'C:\Software\DRAT\DRAT*serverpath*\SoftwareReleaseTool\Trunk\ReleaseNotesTemplates\ReleaseNotes1.docx'"
I want the filename to be
"serverpath\SoftwareReleaseTool\Trunk\ReleaseNotesTemplates\ReleaseNotes1.docx"
The first part, "C:\Software\DRAT\DRAT\" is the directory that the project is in. I cannot find out why it keeps looking in this directory for the server link.
I watch the local values before the function is run and they are correct. I get
"serverpath/Fusion/Main\Releases\Notes\VCM-1.1.43-SoftwareReleaseNotes.docx"
for notes.ReleaseNotesPath and
"serverpath/SoftwareReleaseTool/Trunk/ReleaseNotesTemplates/ReleaseNotes1.docx"
for templatePath.
If I use the paths to the same files that are on my local drive it works, but I need to use the SVN server links so that my co-workers can access the same file from their computers.
Here is the file.copy function that is called:
File.Copy(templatePath, notes.ReleaseNotesPath, true);
templatePath is filled out by the user, where I input "serverpath/SoftwareReleaseTool/Trunk/ReleaseNotesTemplates/ReleaseNotes1.docx"
notes.ReleaseNotesPath is defined here:
notes.ReleaseNotesPath = buildFiles[0] + #"\Releases\Notes\VCM-" + model.ReleaseVersion + "-SoftwareReleaseNotes.docx";
the buildFiles[0] part of it is "serverpath/FusionTest/Main"
I should be making new word document but instead I keep getting the same IOException every time.
File.Copy only works in your local file system. You should try something like System.Net.WebClient.DownloadFile
e.g:
using (var client = new WebClient())
{
client.DownloadFile("https://ags-iv-engrpub/svn/SoftwareReleaseTool/Trunk/ReleaseNotesTemplates/ReleaseNotes1.docx", "ReleaseNotes1.docx");
}
I have this web application project which requires a better user-interface and I am doing it by C#.
I already have my html file with JS done but I need some data from user.
In my JS embedded in HTML file, I used the code below to find the file on local driver and get the data from that excel file and then put all these data into an array.
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open(file1);
var excel_sheet = excel.Worksheets("Sheet1");
However, the "file1" you see above seems to require a full name path,say "C:\test.xls" in my case.
I am new to C# and just built a button on my form design, by clicking the button, I seem to be able to browse my local file.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
System.Diagnostics.Process.Start(file);
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
So, my question:
How can I get this kind of full file path of an uploaded file in C# ?
And furthermore, it would be awesome if some one can tell me how to get this value into my javascript or HTML!
Thank you in advance
You won't be able to depend on getting the full path. In the end, the browser only needs to multi-part encode the physical file and submit it as a form post (of sorts). So once it has it's location and has encoded it -- it's done using it.
It's considered a security risk to expose the file structure to Javascript/HTML (ie., the internet).
Just an update.
I used another logic and it worked as expected. Instead of getting absolute file path , I managed to open the file , save it as somewhere and make my html call find that file path no matter what.
I want to load a xml document Swedish.xml which exists in my solution. How can i give path for that file in Xamarin.android
I am using following code:
var text = File.ReadAllText("Languages/Swedish.txt");
Console.WriteLine("text: "+text);
But i am getting Exception message:
Could not find a part of the path "//Languages/swedish.txt".
I even tried following lines:
var text = File.ReadAllText("./Languages/Swedish.txt");
var text = File.ReadAllText("./MyProject/Languages/Swedish.txt");
var text = File.ReadAllText("MyProject/Languages/Swedish.txt");
But none of them worked. Same exception message is appearing. Build Action is also set as Content. Whats wrong with the path? Thanks in advance.
Just try with this
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Languages", "Swedish.txt");
var text = File.ReadAllText(startupPath);
Try...
Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments)+"/Languages/Swedish.txt"
If you mark a file as Content Type, it will be included in the app bundle with the path that you are using within your project file. You can inspect the IPA file (it's just a renamed zip) that is created to verify that this is happening.
var text = File.ReadAllText("Languages/Swedish.txt");
should work. The file path is relative to the root of your application. You need to be sure that you are using the exact same casing in your code that the actual file uses. In the simulator the casing will not matter, but on the device the file system is case sensitive, and mismatched casing will break the app.
I've looked into this before and never found any solution to access files in this way. All roads seem to indicate building them as "content" is a dead end. You can however place them in your "Assets" folder and use them this way. To do so switch the "Content" to "AndroidAsset".
After you have done this you can now access the file within your app by calling it via
var filename = "Sweedish.txt";
string data;
using
(var sr = new StreamReader(Context.Assets.Open(code)))
data = sr.ReadToEnd();
....
I have a web browser in C# that I want to make navigate to a path (html file) on my local pc.
I tried using this:
if (File.Exists(Path + b.HTML))
{
browserCom1.Navigate(Path + b.HTML);
}
The file Exists, but the browser is keep opening an error of Internet Explorer: "cannot find file:///(my path here)"
It is weird because the file is correct. for example if I use:
System.Windows.Forms.OpenFileDialog browseFile = new
System.Windows.Forms.OpenFileDialog();
browseFile.ShowDialog();
String path = browseFile.FileName;
browserCom1.Navigate(path);
and I select the same file that it tried navigating to before, it works.
If I print the above brwseFile File Name to Console(which is the same as my Path+b.HTML by the way), and copy-paste it into the Navigate(...) Function (changing each '\' to '//') it Doesn't work.
I have no Idea what to do.
I tried something else like:
String path=(File.Open(Path + b.HTML, FileMode.Open).Name);
browserCom1.Navigate(path);
but the application keep getting freezed upon this.
I also tried with new URI(path) and all.
How can I simpley navigate to a HTML file on my computer?
You have http slashes, but should have file system slashes, like c:\something\something.html
I had the same problem. Resolved when I cleaned for double \\ in the code.
If that's not your problem - your problem may be some else problem related to parsing from string to uri.
my path was like this: c:\users\someone1\\myFolder\protocol.htm
I am having an xml file like:
<CurrentProject>
// Elements like
// last opened project file to reopen it when app starts
// and more global project independend settings
</CurrentProject>
Now I asked myself wether I should deliver this xml file with above empty elements with the installer for my app or should I create this file on the fly on application start if it does not exist else read the values from it.
Consider also that the user could delete this file and that should my application not prevent from working anymore.
What is better and why?
UPDATE:
What I did felt ok for me so I post my code here :) It just creates the xml + structure on the fly with some security checks...
public ProjectService(IProjectDataProvider provider)
{
_provider = provider;
string applicationPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
_projectPath = Path.Combine(applicationPath,#"TBM\Settings.XML");
if (!File.Exists(_projectPath))
{
string dirPath = Path.Combine(applicationPath, #"TBM");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
using (var stream = File.Create(_projectPath))
{
XElement projectElement = new XElement("Project");
projectElement.Add(new XElement("DatabasePath"));
projectElement.Save(stream, SaveOptions.DisableFormatting);
}
}
}
In a similar scenario, I recently went for creating the initial file on the fly. The main reason I chose this was the fact that I wasn't depending on this file being there and being valid. As this was a file that's often read from/written to, there's a chance that it could get corrupted (e.g. if the power is lost while the file is being written).
In my code I attempted to open this file for reading and then read the data. If anywhere during these steps I encountered an error, I simply recreated the file with default values and displayed a corresponding message to the user.