---
title: "Visual Studio 2008 的缺省文件代码页"
author: "梁利锋"
date: "2008-07-02T17:45:54Z"
tags: []
categories: ["编程语言"]
slug: "visual-studio-2008"
draft: false
lastmod: "2008-07-02T17:45:54Z"
id: 210724
url: "https://llf.iteye.com/blog/210724"
---

本来以为只有非英语国家的程序被英语国际的人看的时候会有代码页问题，不过，还是发现，英语国家的人，也很喜欢使用一些不属于 ASCII 的特殊字符，结果造成那些代码被非英语国家的人使用的时候，也很麻烦。

　　Visual Studio 缺省使用当前 Windows 代码页保存文件，实在是个不可思议的决定，不过，既然发生了，还是要解决。上网查了一下，奇怪的是，很多人问到这个问题，却没有发现提供解决方法。

　　确实，在 Visual Studio 的选项里翻弄了半天，还是没有发现可以设置缺省代码页的地方。

　　最后，在“文件”菜单发现“高级保存选项”，可以设置代码页，再测试一下，这个设置对于新建文件也有效。看来它就是缺省代码页了，只是不知道为什么不放在“选项”对话框中。

　　另外，还有一个问题，就是现有程序怎么办，没有发现现成的工具，就自己写了一个，代码很简单，一个 WinForm 窗口，有一个叫 FileCollector 的 ListBox，一个叫 Run 的按钮，一个叫 FileCount 的 Label，然后是代码：

```c#

// Recode 1.0
// http://llf.hanzify.org
// http://llf.iteye.com
// 作者：梁利锋
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Recode
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void FileCollector_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Link;
        }

        private void FileCollector_DragDrop(object sender, DragEventArgs e)
        {
            var list = (Array) e.Data.GetData(DataFormats.FileDrop);
            if (list != null && list.Length > 0)
            {
                FileCollector.Items.Clear();
                foreach (object f in list)
                {
                    string s = f.ToString();
                    if (File.Exists(s))
                    {
                        FileCollector.Items.Add(s);
                    }
                }
            }
            FileCount.Text = FileCollector.Items.Count.ToString();
        }

        private void Run_Click(object sender, EventArgs e)
        {
            if (FileCollector.Items.Count > 0)
            {
                foreach (string name in FileCollector.Items)
                {
                    RecodeOneFile(name);
                }
                MessageBox.Show("done!");
            }
            else
            {
                MessageBox.Show("Please drag and drop some files to the list box first.");
            }
        }

        private static void RecodeOneFile(string name)
        {
            string content;
            using (var sr = new StreamReader(name, Encoding.GetEncoding(1252))) // 英文代码页
            {
                content = sr.ReadToEnd();
            }

            using (var sw = new StreamWriter(name, false, Encoding.UTF8))
            {
                sw.Write(content);
            }
        }
    }
}

```

　　我个人比较喜欢带签名的 UTF-8 格式，对于源文件的代码页，可以查一下这个[代码页介绍的文章](http://qbit.100steps.net/dhtml/charsets/charset4.html)。