十进制度批量转换度分秒
写在代码之前:
有一条小河,因为怕湿了脚,所以去搭桥。
结果是脚没有湿,却弄脏了全身。
谷歌地图下载器下载的图片四个角点的经纬度坐标为十进制的度,在ArcGIS里做配准,由于图比较大,导出的时候做了分割,
分割成了很多张图片。需要找出其中一张与研究区一致的影像,一个个配准需要输入经纬度,但ArcGIS中输入的是度分秒,
所以,写程序对txt文件进行批量处理。代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace 十进制度转度分秒 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string folderpath = ""; private void button1_Click(object sender, EventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.Description = "选择包含谷歌地图下载器经纬度的文件夹"; if (fbd.ShowDialog() == DialogResult.OK) { folderpath = fbd.SelectedPath; } textBox1.Text = folderpath; } private void button2_Click(object sender, EventArgs e) { char[] split = new char[] { ':', ',' }; //分割字符串 folderpath = textBox1.Text; //获取所选文件夹路径下的所有txt文档 List<string> list = new List<string>(); string[] strlist = Directory.GetFiles(folderpath); for (int i = 0; i < strlist.Length; i++) { FileInfo f = new FileInfo(strlist[i]); if (f.Extension == ".txt") list.Add(strlist[i]); } for (int i = 0; i < list.Count; i++) { try { StringBuilder sb = new StringBuilder(); StreamReader sr = new StreamReader(list[i],Encoding.GetEncoding(936),true); string s; while (!sr.EndOfStream) { s = sr.ReadLine(); string[] tempstr = s.Split(split); if (!tempstr[0].Contains("角")) { MessageBox.Show("所选择的不是谷歌地图下载器的坐标文件"); return; } else { //转换并写入文件 double[] dt1 = trandu2m(tempstr[1]); double[] dt2 = trandu2m(tempstr[2]); string s1 = tempstr[0]+dt1[0].ToString() + "°" + dt1[1].ToString()+"′"+dt1[2].ToString()+"″"; string s2 = dt2[0].ToString() + "°" + dt2[1].ToString() + "′" + dt2[2].ToString() + "″"; sb.AppendLine(s1 + "," + s2); } } sr.Close(); FileStream fs = new FileStream(list[i], FileMode.Append); StreamWriter sw = new StreamWriter(fs,Encoding.GetEncoding(936)); sw.WriteLine(); //写入一空行 sw.WriteLine(sb); sw.Close(); } catch (System.Exception ex) { throw new Exception(ex.Message); } } MessageBox.Show("操作成功"); } /// <summary> /// 十进制度转化为度分秒 /// </summary> /// <param name="str"></param> /// <returns></returns> private double[] trandu2m(string str) { try { //double dd = Convert.ToDouble(str); double[] dt = new double[3]; dt[0] = Convert.ToDouble(str.ToString().Substring(0, str.IndexOf("."))); string str1= str.Substring(str.IndexOf(".")+1); str1 = "0." + str1; string str2 = (Convert.ToDouble(str1) * 60).ToString(); dt[1] = Convert.ToDouble(str2.Substring(0,str2.IndexOf("."))); string str3 = str2.Substring(str2.IndexOf(".") + 1); str3 = "0." + str3; string str4 = (Convert.ToDouble(str3) * 60).ToString(); dt[2] = Convert.ToDouble(str4); return dt; } catch (System.Exception ex) { throw new Exception(ex.Message); } } } }