The LaTeX kernel has a command \zap@space, which is expandable and can be used in file names, e.g.:
\newcommand*{\docnr}{foo bar}
\makeatletter
\edef\docnr@wosp{\docnr\space}
\newcommand{\tocfile}{}
\edef\tocfile{../toc/\expandafter\zap@space\docnr@wosp\@empty.tex}
\makeatother
\typeout{[tocfile=\tocfile]}
Result:
[tocfile=../toc/foobar.tex]
Writing without page numbers
When page numbers are not needed, then deferred writing is not needed and we can use \immediate\write. LaTeX's protection mechanism is supported by
\let\protect\noexpand
while writing the entry. Then \textbf{\docnr} becomes \textbf {foo bar}. TeX adds a space after command names and the other space comes from LaTeX's protected commands, which expand to a macro with the same name except that a trailing space was added to the macro name.
Fragile macros can be protected by prefixing it with \protect as usual. \string can also be used, it avoids the space after the command name.
\documentclass{article}
\newcommand*{\docnr}{foo bar}
\makeatletter
\edef\docnr@wosp{\docnr\space}
\newcommand{\tocfile}{}
\edef\tocfile{\expandafter\zap@space\docnr@wosp\@empty.tex}
\makeatother
% toc file management
\makeatletter
\if@filesw
\let\toc@handle\relax
\DeclareRobustCommand{\addtotoc}[1]{%
\ifx\toc@handle\relax
\newwrite\toc@handle
\immediate\openout\toc@handle=\tocfile\relax
\fi
\begingroup
\let\protect\noexpand
\immediate\write\toc@handle{#1}%
\endgroup
}%
\newcommand*{\closetoc}{%
\immediate\closeout\toc@handle
}%
\else
\newcommand{\addtotoc}[1]{}%
\newcommand*{\closetoc}{}%
\fi
\makeatother
\begin{document}
\addtotoc{\textbf{\docnr}, %
written via macro \string\verb|\string\addtotoc|.}
\closetoc
\input{\tocfile}
\end{document}

File foobar.tex:
\textbf {foo bar}, written via macro \verb|\addtotoc|.
The file can be read before the first \addtotoc and after \closetoc.
Deferred writing with page numbers
\documentclass{article}
\newcommand*{\docnr}{foo bar}
\makeatletter
\edef\docnr@wosp{\docnr\space}
\newcommand{\tocfile}{}
\edef\tocfile{\expandafter\zap@space\docnr@wosp\@empty.tex}
\makeatother
% toc file management
\makeatletter
\if@filesw
\let\toc@handle\relax
\DeclareRobustCommand*{\addtotoc}{%
\ifx\toc@handle\relax
\newwrite\toc@handle
\immediate\openout\toc@handle=\tocfile\relax
\fi
\protected@write\toc@handle{}% + argument of \addtotoc
}%
\newcommand*{\closetoc}{%
\closeout\toc@handle
}%
\else
\newcommand{\addtotoc}[1]{}%
\newcommand*{\closetoc}{}%
\fi
\makeatother
\begin{document}
Hello World!
\addtotoc{\textbf{\docnr} on page \thepage,
written via macro \string\verb|\string\addtotoc|.}
\closetoc
\newpage
\input{\tocfile}
\end{document}

File foobar.tex:
\textbf {foo bar} on page 1, written via macro \verb|\addtotoc|.
The file can be read before the first \addtotoc and after the page, where the deferred \closeout is called.
\openoutshould be something that fully expands to a string, but\nospacesisn't. – egreg Sep 26 '15 at 12:23\tocfile? – Heiko Oberdiek Sep 26 '15 at 16:16