技术开发 频道

VS2010与Win7共舞:UAC与数据重定向

  2 托管代码: 使用System.Environment.GetFolderPath函数,通过指定我们想要获取的“已知文件夹”为参数,从而获取相应的文件夹的正确路径。

  •   Environment.SpecialFolder.CommonApplicationData – 所有用户都可以访问的应用程序数据适合放置在这个目录下。
  •   Environment.SpecialFolder.LocalApplicationData – 每个用户单独访问的应用程序数据适合放置在这个目录下。
  •   Environment.SpecialFolder.ApplicationData – 每个用户单独访问的应用程序数据适合放置在这个目录下。这是“随身文件夹”。

  下面这段代码展示了如何在托管代码中获取正确的文件路径:

internal class FileIO
    {
        
private const string AppFolderName = "YourApp";
        
private const string DataFileName = "SomeFile.txt";
        
private static string _dataFilePath;

        
/// <summary>
        
/// 构建路径
        
/// </summary>
        static FileIO()
        {
            
// Environment.GetFolderPath返回一个“已知文件夹”的路径
            
// Path.Combine可以合并两个路径成一个合法的路径

            
//
            
            _dataFilePath
= Path.Combine(Environment.GetFolderPath(
                  Environment.SpecialFolder.ProgramFiles), AppFolderName);
            
//错误的做法:
            
//_dataFilePath = Path.Combine(Environment.GetFolderPath(
             Environment.SpecialFolder.CommonApplicationData), AppFolderName);
            
            
// 扩展文件名
            _dataFilePath = Path.Combine(_dataFilePath, DataFileName);
        }

        
public static void Save(string text)
        {
            
// 检查要保存的字符串是否为空
            if (String.IsNullOrEmpty(text))
            {
                MessageBox.Show(
"字符串为空,无法保持.", "空字符串",
                     MessageBoxButtons.OK, MessageBoxIcon.Error);
                
return;
            }

            
try
            {
                
// 获取文件保存的路径
                string dirPath = Path.GetDirectoryName(_dataFilePath);
                
// 检查文件夹是否存在
                if (!Directory.Exists(dirPath))
                    Directory.CreateDirectory(dirPath);
// 创建文件夹
            }
            
catch (Exception ex)
            {
                MessageBox.Show(ex.Message,
"文件夹创建失败",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                
return;
            }

            
try
            {
                
// 保存字符串到文件
                StreamWriter sw = new StreamWriter(_dataFilePath);
                
try
                {
                    sw.Write(text);
                }
                
finally
                {
                    
// 关闭文件
                    sw.Close();
                }
            }
            
catch (Exception ex)
            {
                MessageBox.Show(ex.Message,
"文件写入失败",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
//
   }
}

        如果上面的方法都不适合你,你还可以使用环境变量获取相应的文件夹路径:

  •   %ALLUSERSPROFILE% – 所有用户都可以访问的应用程序数据适合放置在这个目录下。
  •   %LOCALAPPDATA% – 每个用户单独访问的应用程序数据适合放置在这个目录下。 - (Windows Vista 或者Windows 7)
  •   %APPDATA% – 每个用户单独访问的应用程序数据适合放置在这个目录下。这是“随身文件夹”。- (Windows Vista 或者Windows 7)
0
相关文章