💭
jsを使ってファイル操作が可能なソフトを作成しました
実行ファイル名 js_file_writer.exe
技術
C# windows form
webview
作成した理由
簡単なファイル操作をするようなソフトウェアを作成する際に、
C#で作ると見た目がきれいにできないので、htmlを表示して、ファイル操作もできるようになったらいいなということで作成しました。
使用方法
exeのソフトを起動すると、srcの中のindex.htmlが読み込まれ、
それをソフトウェアとして認識する。
起動時に一回のみ、ファイルをやり取りするためのコードをhtml側に読み込ませるので、リンク遷移などをすると、ファイル操作ができなくなります。
実際のコードはこちら
<!DOCTYPE html>
<html lang="ja">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<script language="javascript" type="text/javascript">
//C#から呼び出すための関数
function func1(str1) {
alert("C# called>" + str1);
return "success"
}
function ButtonClick() {
// テキストエリアから値を取得
const folderPath = document.getElementById('folderPath').value;
const textContent = document.getElementById('textContent').value;
// 入力値のバリデーション
if (!folderPath || !textContent) {
alert("フォルダパスとテキスト内容を両方入力してください");
return;
}
try {
//C#の関数の実行(入力値を使用)
chrome.webview.hostObjects.class.txt_write(folderPath, textContent);
alert("ファイルの書き込みが完了しました");
} catch (error) {
alert("エラーが発生しました: " + error.message);
}
}
async function readClick(){
// テキストエリアから値を取得
const folderPath = document.getElementById('folderPath').value;
const textContent = document.getElementById('textContent').value;
// 入力値のバリデーション
if (!folderPath) {
alert("フォルダパスを入力してください");
return;
}
try {
//C#の関数の実行(入力値を使用)
document.getElementById('textContent').value = await chrome.webview.hostObjects.class.txt_read(folderPath);
alert("ファイルの読み込みが完了しました");
} catch (error) {
alert("エラーが発生しました: " + error.message);
}
}
async function deleteClick(){
// テキストエリアから値を取得
const folderPath = document.getElementById('folderPath').value;
// 入力値のバリデーション
if (!folderPath) {
alert("フォルダパスを入力してください");
return;
}
try {
//C#の関数の実行(入力値を使用)
document.getElementById('textContent').value = await chrome.webview.hostObjects.class.file_delete(folderPath);
alert("ファイルの削除が完了しました");
} catch (error) {
alert("エラーが発生しました: " + error.message);
}
}
</script>
</head>
<body>
<h1>ファイル書き込みサンプル</h1>
<div style="margin-bottom: 10px;">
<label for="folderPath">保存先フォルダパス(相対パス):</label><br>
<input type="text" id="folderPath" style="width: 300px;"
value="js_create\\sample.txt">
</div>
<div style="margin-bottom: 10px;">
<label for="textContent">保存するテキスト内容:</label><br>
<textarea id="textContent" rows="40" style="width: 300px;"
placeholder="ここに保存したいテキストを入力してください"></textarea>
</div>
<input type="button" value='ファイルに書き込む' onclick="ButtonClick();"/>
<input type="button" value='ファイルを読みこむ' onclick="readClick();"/>
<input type="button" value='ファイルを削除' onclick="deleteClick();"/>
</body>
</html>
ファイルの読み書きは基本、相対パスです。
実行ファイルの場所から見て、どこに保存するかを指定します。
フォルダがない場合、作成されます。
セキュリティに関しては何も考えていませんので、すべて自己責任の範囲で使用してください。
Discussion