保存由C#中的特定进程打开的文件

时间:2013-05-29 17:15:56

标签: c# regex batch-file process file-extension

我正在使用公共域中不存在的文件类型。该文件是二进制或十六进制,但是当您双击某个文件以便在记事本中将其打开为.txt文件时,会编写一个先前的批处理文件。

我要做的是在程序中打开此文件,然后在打开时将其保存,以便它现在是.txt文件,我可以使用它。

所以我开始批处理文件进程,文件本身就是参数。

/*Start the  batch file and open file (as an argument)
         * Then it'll be viewable as a text file 
         * */
        Process process = new Process();
        process.StartInfo.FileName = "C:/batchfile.bat";
        process.StartInfo.Arguments = "C:/file.ext";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.Start();

然后,我使用Regex查看当前正在运行的进程是否具有文件扩展名并且是否在记事本中运行:

/*Using a regex pattern, we can see if a wtd file has been opened
         * If there is, it's added to an array called matchArr
         * */

String pattern = "^.*ext.*Notepad.*$";
        Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
        Process[] processes = Process.GetProcesses();
        int useMatch = 0;
        String[] matchArr = new String[100];
        foreach (var proc in processes)
        {
            MatchCollection matches = rgx.Matches(proc.MainWindowTitle);
            if (!string.IsNullOrEmpty(proc.MainWindowTitle))

                if (matches.Count > 0)
                {

                    useMatch = matches.Count;
                    for (int i = 0; i < useMatch; i++)
                    {
                        matchArr[i] = proc.MainWindowTitle;
                        String blah = proc.Modules[0].FileName;
                        string path = System.IO.Path.GetFullPath(proc.MainWindowTitle);

                        Console.WriteLine("Path:" +path);
                        StreamReader stream = new StreamReader(blah);
                        FileStream fstr = new FileStream("C:/newName.txt", FileMode.Create, FileAccess.Write);
                        using (StreamWriter strw = new StreamWriter(fstr))
                        {
                            strw.WriteLine(stream);
                            Console.WriteLine("Array is : " + matchArr[i].ToString());
                        }
                    }
                }
        }

我一整天都在谷歌上搜索 - 我的方法一定是在某处出错了,但我认为要弄清楚这一点并不是那么困难。任何帮助都会非常感激 - 我也不是C#的本地人,所以请原谅任何糟糕的编码习惯。

有人可以帮我弄清楚如何将此文件更改为.txt文件吗?另外,C#显然不会将其读作.txt,因此我不能像记事本一样更改文件扩展名,这就是为什么我要这样做。我也花了很多时间搞乱编码,但无济于事。

1 个答案:

答案 0 :(得分:0)

如果是二进制文件,您可以将其转换为文本并保存:

string myString;
using (FileStream fs = new FileStream(YourBinaryFile, FileMode.Open))
using (BinaryReader br = new BinaryReader(fs))
{
    byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
    myString = Convert.ToBase64String(bin);
}

然后你可以用这种方式把它写成文件:

File.WriteAllText(YourTargetTxtFile, myString);

或者根据需要使用它。 希望有所帮助!

编辑:

你也可以使用这个函数指定编码,重载:

File.WriteAllText(file, contents, encoding);