c#String.Format抛出"输入异常无效"

时间:2015-12-08 18:00:47

标签: c# string templates string.format

我正在编写一个c#控制台程序,该程序读取配置文件并找到了in google dev website.的谷歌地图示例。我将html内容复制到本地模板文件中,并为string.format添加占位符(请注意下面的代码中的{1},{2}。

然后,我从本地文件系统中读取模板,并使用下面的代码填充占位符。问题是string.format不断抛出错误Input string was not in a correct format.如果我用空白文件替换模板,则不会抛出Input string was not in a correct format.。没有例外。因此,问题在于下面的html模板而不是代码。是否有人可以通过模板发现问题,使其无法与string.format一起使用?我猜测它与{}有关,所以我移动了任何双倍(即{{),但这并没有帮助。

代码

  var res = string.Format(template,
                ConfigurationManager.AppSettings["PageTitle"],
                ConfigurationManager.AppSettings["zoom"],
                ConfigurationManager.AppSettings["CenterLat"],
                ConfigurationManager.AppSettings["CenterLongi"],
                ConfigurationManager.AppSettings["mapTypeId"],
                 sb.ToString(),
                ConfigurationManager.AppSettings["strokeColor"],
                ConfigurationManager.AppSettings["strokeOpacity"],
                ConfigurationManager.AppSettings["strokeWeight"],
                ConfigurationManager.AppSettings["fillColor"],
                ConfigurationManager.AppSettings["fillOpacity"],
                  ConfigurationManager.AppSettings["GoogleMapBaseUrl"].Replace("_KEY_",          ConfigurationManager.AppSettings["APIKey"])

                );

HTML模板

<!DOCTYPE html>
<html>
 <head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>{0}</title>
<style>
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }

    #map {
        height: 100%;
    }
</style>
</head>
<body>
<div id="map"></div>
<script>


function initMap() {
 var map = new google.maps.Map(document.getElementById('map'), {
  zoom: {1},
  center: {  
      lat: {2}, lng: {3}   
  },
  mapTypeId: {4}
 });

 // Define the LatLng coordinates for the polygon's path.
  var triangleCoords = [

 {5}
 ];

 // Construct the polygon.
 var bermudaTriangle = new google.maps.Polygon(

  {
  paths: triangleCoords,
  strokeColor: '{6}',
strokeOpacity: {7},
strokeWeight: {8},
fillColor: '{9}',
fillOpacity: {10}


  });
  bermudaTriangle.setMap(map);
}

 </script>
 <script async defer
        src="{11}"></script>
 </body>
  </html>

1 个答案:

答案 0 :(得分:1)

在字符串中出现花括号作为文字会导致string.Format在解析时失败。您应该在模板中使用此语法 (仅显示代码的一部分)

function initMap() {{
 var map = new google.maps.Map(document.getElementById('map'), {{
  zoom: {1},
  center: {{  
      lat: {2}, lng: {3}   
  }},
  mapTypeId: {4}
 }});
相关问题