ClickOnceデータディレクトリを使用するコードがデバッグ実行できない
以前こちらの投稿でDataDirectory プロパティを使用したClickOnceによる更新でローカルデータを引き継ぐコードを書きましたが、このコードを普通にデバッグ実行すると、InvalidOperationExceptionが発生します。
おそらくは、データディレクトリはClickOnceで発行したアプリケーションにしか存在しないために発生しているのだと思いますが、デバッグできないのはちょっと困りますね。
というわけで、IsNetworkDeployed プロパティを使ってClickOnce アプリケーションかどうかを判定するようにコードを変更しました。
Visual Basicの場合であれば、My.Application.IsNetworkDeployed プロパティ | Microsoft Docsでも同じようです。
Imports System.IO
Imports System.Deployment.Application
Public Class Form1
Private myPath As String
' 読み込む
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If (ApplicationDeployment.IsNetworkDeployed) Then
' ClickOnceアプリケーション
myPath = Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "appDataDirTest.txt")
Else
' 非ClickOnceアプリケーション
myPath = Path.Combine(Application.StartupPath, "appDataDirTest.txt")
End If
' ファイルが既に存在するか?
If System.IO.File.Exists(myPath) Then
' Shift-JISエンコーディングでテキストファイルを開く
Dim sr As New System.IO.StreamReader(myPath, System.Text.Encoding.GetEncoding(932))
' 内容をすべて読み込む
TextBox1.Text = sr.ReadToEnd()
' 閉じる
sr.Close()
End If
End Sub
' 書き込む
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
' ファイルを上書きする
Dim sw As New StreamWriter(myPath, False, System.Text.Encoding.GetEncoding(932))
' TextBox1.Textの内容をすべて書き込む
sw.Write(TextBox1.Text)
' 閉じる
sw.Close()
End Sub
End Class
Imports System.Deployment.Application
Public Class Form1
Private myPath As String
' 読み込む
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If (ApplicationDeployment.IsNetworkDeployed) Then
' ClickOnceアプリケーション
myPath = Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "appDataDirTest.txt")
Else
' 非ClickOnceアプリケーション
myPath = Path.Combine(Application.StartupPath, "appDataDirTest.txt")
End If
' ファイルが既に存在するか?
If System.IO.File.Exists(myPath) Then
' Shift-JISエンコーディングでテキストファイルを開く
Dim sr As New System.IO.StreamReader(myPath, System.Text.Encoding.GetEncoding(932))
' 内容をすべて読み込む
TextBox1.Text = sr.ReadToEnd()
' 閉じる
sr.Close()
End If
End Sub
' 書き込む
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
' ファイルを上書きする
Dim sw As New StreamWriter(myPath, False, System.Text.Encoding.GetEncoding(932))
' TextBox1.Textの内容をすべて書き込む
sw.Write(TextBox1.Text)
' 閉じる
sw.Close()
End Sub
End Class
ちなみに、MSDNの下記のページでは、日本語だとサンプルコードがないのですが英語のほうにはIsNetworkDeployedプロパティを使ったサンプルコードが書いてあります。
日本語
英語