open window explorer folder from my results c# - c#

iv made a web forum, as i have lots of folders on my local drive i can now search for any folders i want on webpage.
Now am looking to add a link to the results of the search so it takes me directly to the folder.
My code in c#:
protected void List_Dirs(string searchStr = null)
{
try
{
MainContentLocal.InnerHtml = "";
string[] directoryList = System.IO.Directory.GetDirectories("\\\\myfiles\\Web");
int x = 0;
foreach (string directory in directoryList)
{
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text = "Your Search for : <strong>" + SearchPhrase.Text + "</strong> returns ";
if(directoryP.ToLower().Contains(searchStr.ToLower()))
{
MainContentLocal.InnerHtml += directoryP + "<br />";
x++;
}
}
else
{
MainContentLocal.InnerHtml += directoryP + "<br />";
}
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text += "<strong>" + x.ToString() + "</strong> results";
UserInfo.CssClass = "userInfo";
}
}
catch(Exception DirectoryListExp)
{
MainContentLocal.InnerHtml = DirectoryListExp.Message;
}
}
When i enter something is search i will get a list of folders like:
Your Search for : project returns 2 results
job234 project234 Awards
job323 project game
now is there any way for me to click the result so i can open a window explore on the webpage
Thanks

You can create links like project234.
string folder = "\\\\myfiles\\Web";
if (string.IsNullOrWhiteSpace(Request["folder"])) {
// Folder clicked
folder = string.Format("{0}{1}", folder, Request["folder"]);
Process.Start(folder);
}
string[] directoryList = System.IO.Directory.GetDirectories(folder);
Then it will open it on the server. So if it really is local, than it will work. If there is no security problem. But I'm not sure. You can also use file:// links (as Ryan Mrachek notes), but browsers are not happy to let you open them.

If your result is a file, you can open that file programmatically through the Process class by invoking Process.Start("C:\\MyResults.txt"). This will open the results in the default text editor. In the same way, you can also open a web page by inserting passing a Url to Process.Start. I hope this is what wanted.

our file urls are malformed. It should be:
file:///c:/folder/
Please refer to The Bizarre and Unhappy Story of File URLs.
This works for me:
link
When you click Link, a new Windows Explorer window is opened to the specified location. But as you point out, this only works from a file:// URL to begin with.
A detailed explanation of what is going on can be found here. Basically this behavior by design for IE since IE6 SP1/SP2 and the only way you can change it is by explicitly disabling certain security policies using registry settings on the local machine.
So if you're an IT admin and you want to deploy this for your internal corporate LAN, this might be possible (though inadvisable). If you're doing this on some generic, public-facing website, it seems impossible.

Related

Acces denied when FileUpload from temp folder to SPDocumentLibrary

As an unexperienced developer I have no idea whether this question is phrased properly (I did check the internet but I havent found a solution that worked for me that is why I signed up here). I am trying to make a form where users can upload files to attach to their form (in SharePoint 2013) and I used the following code as an example. The idea is to temporary accept the files and display them to the user and upload them to the document library when the form is submitted.
In my code however, this results in "acces denied" and when I debugged it, the following piece of my code seemed to be causing the problem:
public void BtnAttachmentUpload_Click(object sender, EventArgs e)
{
fileName = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);
if (fileName != "")
{
string _fileTime = DateTime.Now.ToFileTime().ToString();
string _fileorgPath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string _newfilePath = _fileTime + "~" + fileName;
length = (FileUpload.PostedFile.InputStream.Length) / 1024;
string tempFolder = Environment.GetEnvironmentVariable("TEMP");
string _filepath = tempFolder + "\\" + _newfilePath;
FileUpload.PostedFile.SaveAs(_filepath);
AddRow(fileName, _filepath, DocNo, true);
DocNo = DocNo + 1;
Label.Text = "Successfully added in list";
}
}
The last line of the first section(FileUpload.PostedFile.SaveAs(_filepath);) is where it gives the following error:
"System.UnauthorizedAccessException: 'Access to the path
'C:\Users\Spapps\AppData\Local\Temp\131613662837501509~testdoc2.pdf'
is denied.' "
Is this a known issue and is there a solution that can help me out?
Try with spsecurity.runwithelevatedprivileges
I've been looking to close this question but didnt find how to so Ill state it here as an answer. I havent found a solution, but I worked around this issue in my project by altering the approach; I do not temporarily upload and display the files anymore. They are deleted from the doclib if the procedure is cancelled.

Open link in browser from code behind of installed application C#

I have made a winform application. When I run the app in visual studio, following code works to open a link from DataGridView link column.
System.Diagnostics.Process.Start("chrome.exe",
grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
But when I install the build and try to do the same thing, nothing happens. Is there any other setting that I need to make.
Please help.
If you want to open link link from your DataGridView, you should actually pass url not web browser, ie.:
System.Diagnostics.Process.Start(grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString());
It will end up trying to open given url with default browser for OS.
Ofc make sure that link of url from url is properly formatted.
If chrome.exe doesn't work for launching, maybe try shortened one: chrome?
Can you also confirm that Win+R (a.k.a. Run...) and then chrome.exe actually opens up Chrome?
If not, can you check if
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\ contains chrome.exe entry?
If so, maybe url formatting is wrong?
You can open a URL in browser with the following snippets:
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = "http://google.com";
process.Start();
or
System.Diagnostics.Process.Start("http://google.com");
In your example, to allow users to launch it from the DataGridView, you should simply define a click event like this:
private void grdRelLinks_CellContentClick(object pSender, DataGridViewCellEventArgs pArgs)
{
if (pArgs.RowIndex > -1 && pArgs.ColumnIndex == 2)
{
string url = grdRelLinks.Rows[pArgs.RowIndex].Cells[pArgs.ColumnIndex].Value.ToString();
if(!string.IsNullOrWhiteSpace(url))
System.Diagnostics.Process.Start(url);
}
}
This worked for me.
private void OnGridViewContentClick(object sender, EventArgs e)
{
string chromeExePath = CheckIfChromeIsInstalled();
if (!string.IsNullOrEmpty(chromeExePath))
{
MessageBox.Show("Yayy Chrome.exe was found !");
//Path is not null:
Process.Start(chromeExePath, "http://www.google.de");//Here you can also enter the URL you get from your GridView
string url = grdRelLinks.Rows[e.RowIndex].Cells[2].Value.ToString();
if(!url.StartsWith("http")
{
url = $"http://{url}";
}
Process.Start(chromeExePath, url);
}
else
{
MessageBox.Show("Chrome.exe not found");
}
}
private string CheckIfChromeIsInstalled()
{
DirectoryInfo programFiles = new DirectoryInfo(Environment.GetEnvironmentVariable("PROGRAMFILES"));//Find your Programs folder
DirectoryInfo[] dirs = programFiles.GetDirectories();
List<FileInfo> files = new List<FileInfo>();
Parallel.ForEach(dirs, (dir) =>
{
files.AddRange(dir.GetFiles("chrome.exe", SearchOption.AllDirectories)); //Search for Chrome.exe
});
//files should only contain 1 entry
//Return path of chrom.exe or null
return (files.Count > 0) ? files[0].FullName : null;
}
NOTE: Starting this in an extra Thread could be useful !
EDIT :
Can you please check if cmd.exe works with start chrome.exe "your URL" ?!

.NET/C# How to render static HTML from a separate folder with relative referenced content

I'm developing a custom CMS. I have content per ResearchArticle stored in Azure blobs. The content consists of an index.html file with any related images, pdf's etc. the index.html page uses relative local references as in:
<img src="chuck-norris-1.jpg" />
This is so our designer can make articles with related content and put it all in one folder to be sent to an Azure blob container. Each web server then downloads the content into a local ResearchArticle content folder structure as in:
ResearchArticleBodyLocal\abc
So, now I have to display this content when someone views the article. I was reading the index.html into a string and using #Html.raw(). Problem is, from the view, the relative references aren't working because the view, obviously, is in a different location than the content.
but #1 the relative references are off, and #2 for some reason it's running the action method twice as if it has a jQuery problem, but I'm not using any JQuery here...
Here's what I'm trying:
controller method-
ravm.ArticleBodyIndexHtmlPath = System.IO.File.ReadAllText(Server.MapPath(ConfigurationManager.AppSettings["ResearchArticleBodyRelativeLocalDirectory"] + researchArticle.BodyRelativeLocalPath + "/index.html"));
View -
#(Html.Raw(Model.ArticleBodyIndexHtmlPath))
I've also tried this solution but the relative reference thing is still a problem... Anyone have a vision of how to solve this without having the designer put the intended directory structure into the content references?
You could perhaps put the directory structure there using a bit of string replacement/regex? I do that within my own templating system so that the designer can do src="chuck-norris.jpg" and I replace it depending on the site being hit with src="/othersite-image-dir/chuck-norris.jpg" automatically. That way my designer doesn't have to remember directories.
The other way around it is to have a specific directory structure for your objects, i.e
images
js
css
That way the designer can go src="/js/my-chuck-norris.js" and always hit the file regardless of which site it's in
Yes, I wound up doing this:
private List<string> GetFilePathsAndUpdateIndexHtml(string bodyFolderChoices, string containerName)
{
// get path to each item
var filePaths =
Directory.GetFiles(
Server.MapPath(ConfigurationManager.AppSettings["ResearchArticleFTPUploadRoot"] + "/" +
bodyFolderChoices));
// get root from web.config
var azureRootUrl = ConfigurationManager.AppSettings["AzureBlobRootUrl"] + containerName + "/";
// find index.html and replace relative references
foreach (var s in filePaths)
{
if (s.Contains("index.html"))
{
var doc = new HtmlDocument();
doc.LoadHtml(System.IO.File.ReadAllText(s));
HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//*[#background or #lowsrc or #src or #href]");
if (links == null)
continue;
foreach (HtmlNode link in links)
{
// references to outside URLs this will break unless we check for 'http' and leave alone
if (link.Attributes["background"] != null && !link.Attributes["background"].Value.Contains("http"))
link.Attributes["background"].Value = azureRootUrl + link.Attributes["background"].Value;
if (link.Attributes["href"] != null && !link.Attributes["href"].Value.Contains("http"))
link.Attributes["href"].Value = azureRootUrl + link.Attributes["href"].Value;
if (link.Attributes["lowsrc"] != null && !link.Attributes["lowsrc"].Value.Contains("http"))
link.Attributes["lowsrc"].Value = azureRootUrl + link.Attributes["lowsrc"].Value;
if (link.Attributes["src"] != null && !link.Attributes["src"].Value.Contains("http"))
link.Attributes["src"].Value = azureRootUrl + link.Attributes["src"].Value;
}
doc.Save(s);
}
}
return filePaths.ToList();
}

How to change home page in Internet Explorer using C#?

Is it possible to change home page in Internet Explorer in C# application? Solution for other browsers (Firefox, Chrome) would be also nice.
Well, for IE, you have to set registry key:
HKCU\Software\Microsoft\Internet Explorer\Main\Start Page
For firefox, you will need to edit the js file: prefs.js.
This can be found in: C:\Users\ [USERNAME]\AppData\Roaming\Mozilla\Firefox\Profiles\ [User Subfolder]
Chrome, Stores it data in:
C:\Users\<username>\AppData\Local\Chromium\User Data\Default folder in a Preferences file.
This is in JSON format. Editing it shouldn't be trouble
The home page for Internet Explorer is held in the Start Page registry key at HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main (according to this), so you can set it using the Registry class in Microsoft.Win32 (from this example):
RegistryKey startPageKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\Main", true);
startPageKey.SetValue("Start Page", "http://stackoverflow.com");
startPageKey.Close();
Don't know about the others, I'm afraid.
IE: edit the registery key HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\Start Page
Firefox: find the settings in the profile folder (you will need to parse the file)
Chrome: find the default 'homepage' setting in the preferences file: C:\Users\%USERNAME%/AppData\AppData\Local\Google\Chrome\User Data\Default
For the registry use the .NET RegistryKey class. For the files you will need to parse the files and modify them.
Yes you can. The home page is stored in the registry. As long as your C# program has rights to modify the registry, you should be able to change this entry to any page you want.
IE
[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main]
“Start Page”=”http://www.yourwebsite.com/”
How to modify the Window Registry
How to set the default browser home page (IE) with C#?
FireFox
Firefox does not store the home page in the registry because it has
different profiles under $APPDATA\Mozilla\Firefox\Profiles[profile
name] The file you need to read from is prefs.js, and the line:
user_pref("browser.startup.homepage", .... );
To get the default profile you need to read
$APPDATA\Mozilla\Firefox\profiles.ini. You'll have to loop through
each [Profile#] until Default=1 and you'll have your profile name from
Path=...
If you want me to put this into a function (sounds like a good idea
too) or if you'd like to make it, then get it up on the Wiki.
-Stu
Source
Untested code from experts-exchange
public static void SetMozilla(string strURL)
{
try
{
string strSystemUname = Environment.UserName.ToString().Trim();
string systemDrive = Environment.ExpandEnvironmentVariables("%SystemDrive%");
string strDirectory = "";
string strPrefFolder = "";
if (Directory.Exists(systemDrive + "\\Documents and Settings\\" + strSystemUname + "\\Application Data\\Mozilla\\Firefox\\Profiles"))
{
strDirectory = systemDrive + "\\Documents and Settings\\" + strSystemUname + "\\Application Data\\Mozilla\\Firefox\\Profiles";
}
else if (Directory.Exists(systemDrive + "\\WINDOWS\\Application Data\\Mozilla\\Firefox\\Profiles"))
{
strDirectory = systemDrive + "\\WINDOWS\\Application Data\\Mozilla\\Firefox\\Profiles";
}
if (strDirectory.Trim().Length != 0)
{
System.IO.DirectoryInfo oDir = new DirectoryInfo(strDirectory);
//System.IO.DirectoryInfo[] oSubDir;
//oSubDir = oDir.GetDirectories(strDirectory);
foreach (DirectoryInfo oFolder in oDir.GetDirectories())
{
if (oFolder.FullName.IndexOf(".default") >= 0)
{
strPrefFolder = oFolder.FullName;
CreatePrefs(strURL, strPrefFolder);
}
}
}
}
catch
{ }
}
private static void CreatePrefs(string strURL, string strFolder)
{
StringBuilder sbPrefs = new StringBuilder();
sbPrefs.Append("# Mozilla User Preferences\n\r");
sbPrefs.Append("/* Do not edit this file.\n\r*\n\r");
sbPrefs.Append("* If you make changes to this file while the application is running,\n\r");
sbPrefs.Append("* the changes will be overwritten when the application exits.,\n\r*\n\r");
sbPrefs.Append("* To make a manual change to preferences, you can visit the URL about:config\n\r");
sbPrefs.Append("* For more information, see http://www.mozilla.org/unix/customizing.html#prefs\n\r");
sbPrefs.Append("*/\n\r");
sbPrefs.Append("user_pref(\"app.update.lastUpdateTime.addon-background-update-timer\", 1188927425);\n\r");
sbPrefs.Append("user_pref(\"app.update.lastUpdateTime.background-update-timer\", 1188927425);\n\r");
sbPrefs.Append("user_pref(\"app.update.lastUpdateTime.blocklist-background-update-timer\", 1188927425);\n\r");
sbPrefs.Append("user_pref(\"app.update.lastUpdateTime.search-engine-update-timer\", 1188927425);\n\r");
sbPrefs.Append("user_pref(\"browser.anchor_color\", \"#0000FF\");\n\r");
sbPrefs.Append("user_pref(\"browser.display.background_color\", \"#C0C0C0\");\n\r");
sbPrefs.Append("user_pref(\"browser.display.use_system_colors\", true);\n\r");
sbPrefs.Append("user_pref(\"browser.formfill.enable\", false);\n\r");
sbPrefs.Append("user_pref(\"browser.history_expire_days\", 20);\n\r");
sbPrefs.Append("user_pref(\"browser.shell.checkDefaultBrowser\", false);\n\r");
sbPrefs.Append("user_pref(\"browser.startup.homepage\", \"" + strURL +"\");\n\r");
sbPrefs.Append("user_pref(\"browser.startup.homepage_override.mstone\", \"rv:1.8.1.6\");\n\r");
sbPrefs.Append("user_pref(\"browser.visited_color\", \"#800080\");\n\r");
sbPrefs.Append("user_pref(\"extensions.lastAppVersion\", \"2.0.0.6\");\n\r");
sbPrefs.Append("user_pref(\"intl.charsetmenu.browser.cache\", \"UTF-8, ISO-8859-1\");\n\r");
sbPrefs.Append("user_pref(\"network.cookie.prefsMigrated\", true);\n\r");
sbPrefs.Append("user_pref(\"security.warn_entering_secure\", false);\n\r");
sbPrefs.Append("user_pref(\"security.warn_leaving_secure\", false);\n\r");
sbPrefs.Append("user_pref(\"security.warn_submit_insecure\", false);\n\r");
sbPrefs.Append("user_pref(\"security.warn_submit_insecure.show_once\", false);\n\r");
sbPrefs.Append("user_pref(\"spellchecker.dictionary\", \"en-US\");\n\r");
sbPrefs.Append("user_pref(\"urlclassifier.tableversion.goog-black-enchash\", \"1.32944\");\n\r");
sbPrefs.Append("user_pref(\"urlclassifier.tableversion.goog-black-url\", \"1.14053\");\n\r");
sbPrefs.Append("user_pref(\"urlclassifier.tableversion.goog-white-domain\", \"1.23\");\n\r");
sbPrefs.Append("user_pref(\"urlclassifier.tableversion.goog-white-url\", \"1.371\");\n\r");
StreamWriter writer = new StreamWriter(strFolder + "\\prefs.js");
writer.Write(sbPrefs.ToString());
writer.Close();
writer.Dispose();
GC.Collect();
}
Source
CHROME
Programmatically access the Google Chrome Home or Start page
Other Sources
http://www.howtogeek.com/howto/windows/registry-hack-to-set-internet-explorer-start-page/
http://social.technet.microsoft.com/Forums/en/w7itproinstall/thread/0942e4c4-d8db-4f1a-b638-2550a8dbdbd9
In addition to the above answers, you may want to check the following if there is a group policy in place:
HKCU\Software\Policies\Microsoft\Internet Explorer\Main\Start Page

Add file using SharpSVN

I would like to add all unversioned files under a directory to SVN using SharpSVN.
I tried regular svn commands on the command line first:
C:\temp\CheckoutDir> svn status -v
I see all subdirs, all the files that are already checked in, a few new files labeled "?", nothing with the "L" lock indication
C:\temp\CheckoutDir> svn add . --force
This results in all new files in the subdirs ,that are already under version control themselves, to be added.
I'd like to do the same using SharpSVN. I copy a few extra files into the same directory and run this code:
...
using ( SharpSvn.SvnClient svn = new SvnClient() )
{
SvnAddArgs saa = new SvnAddArgs();
saa.Force = true;
saa.Depth = SvnDepth.Infinity;
try
{
svn.Add(#"C:\temp\CheckoutDir\." , saa);
}
catch (SvnException exc)
{
Log(#"SVN Exception: " + exc.Message + " - " + exc.File);
}
}
But an SvnException is raised:
SvnException.Message: Working copy 'C:\temp\CheckoutDir' locked
SvnException.File: ..\..\..\subversion\libsvn_wc\lock.c"
No other svnclient instance is running in my code,
I also tried calling
svn.cleanup()
right before the Add, but to no avail.
Since the documentation is rather vague ;),
I was wondering if anyone here knew the answer.
Thanks in advance!
Jan
Use this my tool http://svncompletesync.codeplex.com/ or take it as a sample.
It does exactly what you need.
I tried Malcolm's tool but couldn't get it to run now that it looks to be a few years old, but after looking at the source code it looks like this is really all you need to use to sync the local checked out folder with the one in SVN:
string _localCheckoutPath = #"C:\temp\CheckoutDir\";
SvnClient client = new SvnClient();
Collection<SvnStatusEventArgs> changedFiles = new Collection<SvnStatusEventArgs>();
client.GetStatus(_localCheckoutPath, out changedFiles);
//delete files from subversion that are not in filesystem
//add files to suversion , that are new in filesystem
foreach (SvnStatusEventArgs changedFile in changedFiles)
{
if (changedFile.LocalContentStatus == SvnStatus.Missing)
{
client.Delete(changedFile.Path);
}
if (changedFile.LocalContentStatus == SvnStatus.NotVersioned)
{
client.Add(changedFile.Path);
}
}
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "Some message...";
client.Commit(_localCheckoutPath, ca);
I think you shouldn't suffix the path with a ','. Try:
svn.Add(#"C:\temp\CheckoutDir" , saa);
Please do discuss this further on the SharpSvn discussion board/mailing list, because the behavior you are seeing might be a bug.

Categories