简体   繁体   English

如何使Streamwriter在C#的非系统文件夹中创建url链接

[英]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. 我在非系统文件夹中创建url链接(快捷方式)时遇到问题。 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. 如果您的应用程序正在运行oline,则必须在要保存URL的文件夹上为Internet用户设置权限。

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 您也可以像这样添加System.IO.Directory.Exists

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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