简体   繁体   中英

how to make streamwriter create a url link in a non-system folder in C#

I am having a problem with creating a url link (shortcut) in a non-system folder. The link is getting created properly on the desktop without any problem, but if I change the path to a non-system folder the folder remains empty and there is no error message either. Is there a restriction on the paths allowed? Why is there no error message? Code is given below:

private void urlShortcutToFolder(string linkName, string linkUrl)
{
    //string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
    //using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    string nonSystemDir = "C\\Downloads";
    using (StreamWriter writer = new StreamWriter(nonSystemDir + "\\" + linkName + ".url"))
    {
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=" + linkUrl);
        writer.Flush();
    }
}

If you are running your application locally then your code is right. It must work. if your application is running oline then you have to set permission for Internet user on the folder where you want to save your url.

Hope this will solve your problem

For as far I know this no proper path:

string nonSystemDir = "C\\Downloads";

Shouldn't it be

string nonSystemDir = "C:\\Downloads";

or more readable

string nonSystemDir = @"C:\Downloads";

You could also add System.IO.Directory.Exists like so

private void urlShortcutToFolder(string linkName, string linkUrl)
{
    //string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
    //using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    string nonSystemDir = @"C:\Downloads";
    if(!System.IO.Directory.Exists(nonSystemDir))
    {
        throw New Exception("Path " + nonSystemDir + " is not valid");
    }
    using (StreamWriter writer = new StreamWriter(nonSystemDir + "\\" + linkName + ".url"))
    {
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=" + linkUrl);
        writer.Flush();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM